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.
题意:给个数组都是非负整数,不能同时取相邻的两个数,求最大和
思路:用result[i]来指示前i个元素可获得的最大和
遍历每个num[i],
如果前一个房子没被抢劫,则直接加入当前房子的金额 result[i]=result[i-1]+num[i]
如果前一个被劫过,则只有在当前房子金额加前i-1个房子可获得的最大金额之和 大于 前i个房子的最大金额时,才会抢劫当前房子,
即nums[i] + result[i-1] > result[i],否则不抢当前的房子既result[i+1] = result[i];
public int rob(int[] nums) {
if (nums.length == 0) return 0;
if (nums.length == 1) return nums[0];
int result[] = new int[nums.length+1];
result[1] = nums[0];
//indicate whether we robbed the pre house
boolean containLastOne = true;
for (int i=1; i<nums.length; i++) {
if (!containLastOne) {
result[i+1] = result[i] + nums[i];
containLastOne = true;
} else {
result[i+1] = Math.max(nums[i] + result[i-1], result[i]);
containLastOne = result[i+1] == result[i] ? false : true ;
}
}
return result[nums.length];
}