-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution213.java
45 lines (38 loc) · 1.15 KB
/
Solution213.java
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
41
42
43
44
45
package algorithm.leetcode;
/**
* @author: mayuan
* @desc: 打家劫舍 II
* @date: 2018/08/17
*/
public class Solution213 {
public static void main(String[] args) {
int[] nums = {2, 3, 3, 1, 3, 2, 4, 5, 2};
Solution213 test = new Solution213();
System.out.println(test.rob(nums));
}
public int rob(int[] nums) {
if (null == nums || 0 >= nums.length) {
return 0;
}
if (1 == nums.length) {
return nums[0];
}
// 环形街区,数组开头与数组结尾相邻. 返回两种情况最大值
return Math.max(
rob(nums, 0, nums.length - 2),
rob(nums, 1, nums.length - 1));
}
private int rob(int[] nums, int first, int last) {
int pre3 = 0;
int pre2 = 0;
int pre1 = 0;
// 当前位置最大值从 max(前3,前2) 的位置转移过来,(不能取相邻元素)
for (int i = first; i <= last; ++i) {
int current = Math.max(pre3, pre2) + nums[i];
pre3 = pre2;
pre2 = pre1;
pre1 = current;
}
return Math.max(pre2, pre1);
}
}