Skip to content

Commit 59d4806

Browse files
committed
solve house-robber
1 parent fa623a4 commit 59d4806

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

house-robber/samcho0608.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
// * can't rob two adj houses in the same night
3+
// * return: max amount of money robbale in one night
4+
public int rob(int[] nums) {
5+
if(nums.length == 1) return nums[0];
6+
if(nums.length == 2) return Math.max(nums[0], nums[1]);
7+
8+
// maxSum[i] = max sum possible at i (inclusive)
9+
int[] maxSum = new int[nums.length];
10+
maxSum[0] = nums[0];
11+
maxSum[1] = nums[1];
12+
13+
for(int i = 2; i < nums.length; i++) {
14+
if(i == 2) {
15+
maxSum[i] = nums[i] + maxSum[i-2];
16+
continue;
17+
}
18+
19+
// adj houses(i-1) can't be robbed
20+
// choices are:
21+
// 1. i-2 th house (choosing without skipping a house)
22+
// 2. i-3 th house (choosing with skipping a house)
23+
// * choosing < i-4 th houses wouldn't be optimal because it'll be missing either of 1. or 2.
24+
maxSum[i] = nums[i] + Math.max(maxSum[i-2], maxSum[i-3]);
25+
}
26+
27+
return Math.max(maxSum[nums.length-2], maxSum[nums.length-1]);
28+
}
29+
}

0 commit comments

Comments
 (0)