Skip to content

Commit 358388a

Browse files
committed
feat: Add solution for LeetCode problem 213
1 parent 781921c commit 358388a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

house-robber-ii/WhiteHyun.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
//
2+
// 213. House Robber II
3+
// https://leetcode.com/problems/house-robber-ii/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/07/06.
7+
//
8+
9+
class Solution {
10+
func rob(_ nums: [Int]) -> Int {
11+
if nums.count < 3 { return nums.max()! }
12+
var current = 0
13+
var previous = 0
14+
15+
// 첫 번째 집을 턴 경우
16+
for element in nums.dropLast() {
17+
(previous, current) = (current, max(element + previous, current))
18+
}
19+
20+
var current2 = 0
21+
var previous2 = 0
22+
23+
// 첫 번째 집을 털지 않은 경우
24+
for element in nums.dropFirst() {
25+
(previous2, current2) = (current2, max(element + previous2, current2))
26+
}
27+
28+
return max(current, previous, current2, previous2)
29+
}
30+
}

0 commit comments

Comments
 (0)