forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
40 lines (35 loc) · 1.12 KB
/
Solution.java
File metadata and controls
40 lines (35 loc) · 1.12 KB
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
31
32
33
34
35
36
37
38
39
40
public class Solution {
public int rob(int[] nums) {
int dp0 = 0, dp1 = 0, _dp0 = 0, _dp1 = 0;
int n = nums.length;
if (n == 1) return nums[0];
for (int i = 1; i < n; ++i) {
_dp0 = Math.max(dp0, dp1);
_dp1 = Math.max(dp0 + nums[i], dp1);
dp0 = _dp0;
dp1 = _dp1;
}
int result1 = Math.max(dp0, dp1);
dp0 = dp1 = _dp0 = _dp1 = 0;
for (int i = 0; i < n - 1; ++i) {
_dp0 = Math.max(dp0, dp1);
_dp1 = Math.max(dp0 + nums[i], dp1);
dp0 = _dp0;
dp1 = _dp1;
}
int result2 = Math.max(dp0, dp1);
return Math.max(result1, result2);
}
public static void main(String[] args) {
Solution s = new Solution();
int[] nums;
nums = new int[] {1, 2, 3, 4};
System.out.println(s.rob(nums));
nums = new int[] {1, 2, 3};
System.out.println(s.rob(nums));
nums = new int[] {1, 20, 3};
System.out.println(s.rob(nums));
nums = new int[] {1, 20, 30, 30};
System.out.println(s.rob(nums));
}
}