Skip to content

Commit b613632

Browse files
committed
Solution for House Robber #264
1 parent 3187987 commit b613632

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

house-robber/dohyeon2.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public int rob(int[] nums) {
3+
// Dynamic Planning
4+
// Time Complexity: O(n)
5+
// Space Complexity: O(n) for the dp array
6+
// When applying DP, it is important to define the accumulated state clearly.
7+
8+
if (nums.length == 1) {
9+
return nums[0];
10+
}
11+
12+
// The state of dp is maximum amount of robbery at i
13+
int[] dp = new int[nums.length];
14+
15+
dp[0] = nums[0];
16+
dp[1] = Math.max(nums[0], nums[1]);
17+
18+
for (int i = 2; i < nums.length; i++) {
19+
dp[i] = Math.max(
20+
// If we skip the current house,
21+
// we can take the maximum amount of robbery at i - 1
22+
dp[i - 1],
23+
// If we rob the current house, we cannot rob the previous house
24+
// so we can take the maximum amount of robbery at i - 2
25+
dp[i - 2] + nums[i]);
26+
}
27+
28+
return dp[nums.length - 1];
29+
}
30+
}

0 commit comments

Comments
 (0)