Skip to content

Commit e1bc2d3

Browse files
committed
Solve Two House Robber Problems
1 parent 56e12fd commit e1bc2d3

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

house-robber-ii/bky373.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
time: O(N)
3+
time: O(1)
4+
*/
5+
class Solution {
6+
7+
public int rob(int[] nums) {
8+
if (nums.length == 0) {
9+
return 0;
10+
}
11+
if (nums.length == 1) {
12+
return nums[0];
13+
}
14+
15+
return Math.max(
16+
dp(nums, 0, nums.length - 2),
17+
dp(nums, 1, nums.length - 1)
18+
);
19+
}
20+
21+
private static int dp(int[] nums, int start, int end) {
22+
int maxOfOneStepAhead = nums[end];
23+
int maxOfTwoStepsAhead = 0;
24+
25+
for (int i = end - 1; i >= start; --i) {
26+
int curr = Math.max(maxOfOneStepAhead, maxOfTwoStepsAhead + nums[i]);
27+
28+
maxOfTwoStepsAhead = maxOfOneStepAhead;
29+
maxOfOneStepAhead = curr;
30+
}
31+
return maxOfOneStepAhead;
32+
}
33+
}

house-robber/bky373.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
time: O(N)
3+
space: O(1)
4+
*/
5+
class Solution {
6+
7+
public int rob(int[] nums) {
8+
if (nums.length == 0) {
9+
return 0;
10+
}
11+
12+
int maxOfTwoStepsAhead = 0;
13+
int maxOfOneStepAhead = nums[nums.length - 1];
14+
15+
for (int i = nums.length - 2; i >= 0; --i) {
16+
int curr = Math.max(maxOfOneStepAhead, maxOfTwoStepsAhead + nums[i]);
17+
18+
maxOfTwoStepsAhead = maxOfOneStepAhead;
19+
maxOfOneStepAhead = curr;
20+
}
21+
return maxOfOneStepAhead;
22+
}
23+
}

0 commit comments

Comments
 (0)