You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
比如输入是 1,2,4,7,3,5
本来的想法是这样的 对于一个house[i] 他可以抢的上一个house 只有两种情况 即house[i-2]或者house[i-3]
对于3来说 抢的上一个只能是2或者4 不可能是1 因为选择了1 完全可以抢1,4,3
所以 用dp[i]表示到当前house所能抢到的最多钱 dp[i] += Math.max(dp[i-2], dp[i-3])
当i=0,1,2,3的时候还需要特殊处理 最小处理单元是4
public int rob(int[] nums) {
if(nums.length == 0) return 0;
if(nums.length == 1) return nums[0];
if(nums.length == 2) return Math.max(nums[0], nums[1]);
if(nums.length == 3) return Math.max(nums[0]+nums[2], nums[1]);
int[] max = new int[nums.length];
max[0] = nums[0];
max[1] = Math.max(nums[0], nums[1]);
max[2] = Math.max(nums[0]+nums[2], nums[1]);
for(int i=3;i<nums.length;i++){
max[i] = Math.max(max[i-3],max[i-2]) + nums[i];
}
return Math.max(max[max.length-2], max[max.length-1]);
}
尝试着把最小单元缩小为3
1,2,4,7,3,5
首先是1,2,4 对于4来说 最大值是1+4或者2
对于7 最大值是2+7或者到达4位置的最大值
dp[i] = Math.max(dp[i-2]+house[i], dp[i-1])
因为每次只用到上两个计算结果 所以不需要数组存储中间计算值 两个变量就可以了
public int rob(int num[], int n) {
int a = 0;
int b = 0;
for (int i=0; i<n; i++) {
if (i%2==0) {
a = Math.max(a+num[i], b);
} else {
b = Math.max(a, b+num[i]);
}
}
return Math.max(a, b);
}