Skip to content

Commit 9deae0c

Browse files
committed
[DP] Update a solution to House Robber II
1 parent 4863243 commit 9deae0c

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

DP/HouseRobberII.swift

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,25 @@
66
*/
77

88
class HouseRobberII {
9-
func rob(nums: [Int]) -> Int {
10-
guard nums.count != 0 else {
11-
return 0
12-
}
9+
func rob(_ nums: [Int]) -> Int {
1310
guard nums.count != 1 else {
1411
return nums[0]
1512
}
16-
17-
return max(_helper(nums, 0, nums.count - 2), _helper(nums, 1, nums.count - 1))
13+
14+
return max(helper(nums, 0, nums.count - 2), helper(nums, 1, nums.count - 1))
1815
}
1916

20-
private func _helper(nums:[Int], _ start: Int, _ end: Int) -> Int {
21-
var pre = 0, cur = 0, res = 0
17+
fileprivate func helper(_ nums: [Int], _ start: Int, _ end: Int) -> Int {
18+
if start > end {
19+
return 0
20+
}
21+
22+
var prev = 0, current = 0
2223

2324
for i in start...end {
24-
res = max(pre + nums[i], cur)
25-
(cur, pre) = (res, cur)
25+
(current, prev) = (max(prev + nums[i], current), current)
2626
}
2727

28-
return res
28+
return current
2929
}
3030
}

0 commit comments

Comments
 (0)