-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add solution for LeetCode problem 213
- Loading branch information
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
// | ||
// 213. House Robber II | ||
// https://leetcode.com/problems/house-robber-ii/description/ | ||
// Dale-Study | ||
// | ||
// Created by WhiteHyun on 2024/07/06. | ||
// | ||
|
||
class Solution { | ||
func rob(_ nums: [Int]) -> Int { | ||
if nums.count < 3 { return nums.max()! } | ||
var current = 0 | ||
var previous = 0 | ||
|
||
// 첫 번째 집을 턴 경우 | ||
for element in nums.dropLast() { | ||
(previous, current) = (current, max(element + previous, current)) | ||
} | ||
|
||
var current2 = 0 | ||
var previous2 = 0 | ||
|
||
// 첫 번째 집을 털지 않은 경우 | ||
for element in nums.dropFirst() { | ||
(previous2, current2) = (current2, max(element + previous2, current2)) | ||
} | ||
|
||
return max(current, previous, current2, previous2) | ||
} | ||
} |