-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathHouseRobber.java
More file actions
28 lines (22 loc) · 764 Bytes
/
HouseRobber.java
File metadata and controls
28 lines (22 loc) · 764 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package dp_1d;
public class HouseRobber {
public int rob(int[] nums) {
if (nums.length == 0) return 0;
int[] memo = new int[nums.length + 1];
memo[0] = 0;
memo[1] = nums[0];
for (int i = 1; i < nums.length; i++) {
int val = nums[i];
memo[i + 1] = Math.max(memo[i], memo[i - 1] + val);
}
return memo[nums.length];
}
public static void main(String[] args) {
HouseRobber robber = new HouseRobber();
int[] nums1 = {1, 2, 3, 1};
assert robber.rob(nums1) == 4 : "Test case 1 failed";
int[] nums2 = {2, 7, 9, 3, 1};
assert robber.rob(nums2) == 12 : "Test case 2 failed";
System.out.println("All test cases passed!");
}
}