- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem198.java
More file actions
Latest commit
30 lines (25 loc) · 675 Bytes
/
Copy pathProblem198.java
File metadata and controls
30 lines (25 loc) · 675 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
29
30
classProblem198 {
publicstaticvoidmain(String[] args) {
int[] nums = newint[]{2,1,1,2};
System.out.println(newProblem198().rob(nums));
}
publicintrob(int[] nums) {
if (nums.length == 0) return0;
if (nums.length == 1) returnnums[0];
if (nums.length == 2) returnMath.max(nums[0], nums[1]);
int[] sum = newint[nums.length];
sum[0] = nums[0];
sum[1] = nums[1];
// 1 2 9 7 2 1
for (inti = 2; i < nums.length; i++) {
for (intj = 0; j < i-1; j++) {
sum[i] = Math.max(nums[i] + sum[j], sum[i]);
}
}
intmax = sum[0];
for (inti = 1; i < sum.length; i++) {
max = Math.max(max, sum[i]);
}
returnmax;
}
}