https://leetcode.com/problems/house-robber/
显然空间复杂度O(1)的DP问题。rob和notRob记录当前位置抢或者不抢所能获得的最大收益。当前未抢 = max(上次抢了,上次未抢);当前抢了 = 上次未抢 + 当前价值
public class Solution {
public int rob(int[] nums) {
if (nums == null) {
return 0;
}
int rob = 0;
int notRob = 0;
for (int n : nums) {
int curNotRob = notRob;
notRob = Math.max(notRob, rob);
rob = curNotRob + n;
}
return Math.max(rob, notRob);
}
}
https://leetcode.com/problems/house-robber-ii/
如果数组成环。
那么首尾两个只能最多取一个,因此结果为1 ~ len - 1 和 0 ~ len - 2里面较大的那个
public class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
return Math.max(rob(nums, 0, nums.length - 2), rob(nums, 1, nums.length - 1));
}
private int rob(int[] nums, int beg, int end) {
if (nums.length == 1) {
return nums[0];
}
int notRob = 0;
int rob = 0;
for (int i = beg; i <= end; i++) {
int curNotRob = Math.max(notRob, rob);
rob = notRob + nums[i];
notRob = curNotRob;
}
return Math.max(rob, notRob);
}
}