Skip to content

Commit 43c8572

Browse files
committed
house robber ii solution added
1 parent 991efc8 commit 43c8572

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

house-robber-ii/Tessa1217.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
3+
// DP
4+
public int rob(int[] nums) {
5+
int n = nums.length;
6+
7+
if (n == 0) {
8+
return 0;
9+
}
10+
11+
if (n == 1) {
12+
return nums[0];
13+
}
14+
15+
int notRobbingLast = robHouses(nums, 0, n - 2);
16+
int notRobbingFirst = robHouses(nums, 1, n - 1);
17+
18+
return Math.max(notRobbingLast, notRobbingFirst);
19+
}
20+
21+
private int robHouses(int[] nums, int start, int end) {
22+
23+
int length = end - start + 1;
24+
25+
if (length == 0) {
26+
return 0;
27+
}
28+
29+
if (length == 1) {
30+
return nums[start];
31+
}
32+
33+
int[] dp = new int[length];
34+
35+
dp[0] = nums[start];
36+
dp[1] = Math.max(nums[start], nums[start + 1]);
37+
38+
for (int i = 2; i < length; i++) {
39+
dp[i] = Math.max(dp[i - 2] + nums[start + i], dp[i - 1]);
40+
}
41+
42+
return dp[length - 1];
43+
}
44+
}
45+

0 commit comments

Comments
 (0)