Skip to content

Commit 42c0b2e

Browse files
committed
house robber 2
1 parent 00d88fd commit 42c0b2e

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

house-robber-ii/eunhwa99.kt

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// https://leetcode.com/problems/house-robber-ii/description/
2+
class Solution {
3+
fun rob(nums: IntArray): Int {
4+
if (nums.size == 1) return nums[0]
5+
return maxOf(rob(nums, 0, nums.size - 2), rob(nums, 1, nums.size - 1))
6+
}
7+
8+
private fun rob(nums: IntArray, start: Int, end: Int): Int {
9+
val dp = IntArray(nums.size) { 0 }
10+
dp[start] = nums[start]
11+
dp[start + 1] = maxOf(nums[start], nums[start + 1])
12+
for (i in start + 2..end) {
13+
dp[i] = maxOf(dp[i - 1], dp[i - 2] + nums[i])
14+
}
15+
return dp[end]
16+
}
17+
}
18+
// TC: O(n)
19+
// SC: O(n)

0 commit comments

Comments
 (0)