Skip to content

Commit 4c325d2

Browse files
committed
House Robber
1 parent 556a228 commit 4c325d2

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

house-robber/TonyKim9401.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// TC: O(n)
2+
// always need to check every case
3+
// SC: O(n)
4+
// the length of the result int list is same with the length of the given nums int list
5+
class Solution {
6+
public int rob(int[] nums) {
7+
int[] result = new int[nums.length];
8+
9+
if (nums.length < 2) return nums[0];
10+
if (nums.length < 3) return Math.max(nums[0], nums[1]);
11+
12+
result[0] = nums[0];
13+
result[1] = Math.max(nums[0], nums[1]);
14+
15+
for (int i = 2; i < nums.length; i++) {
16+
result[i] = Math.max(result[i - 1], result[i - 2] + nums[i]);
17+
}
18+
19+
return result[nums.length-1];
20+
}
21+
}

0 commit comments

Comments
 (0)