题目链接:https://leetcode.com/problems/house-robber/
题目:
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.
思路:
用n数组表示到当前元素为止的最大值。则n[i]只跟n[i-2]和n[i-1]有关,当n[i-1]大于n[i-2]+nums[i]的时候可以放弃抢劫nums[i],因为抢了还不如不抢,且抢了i-2、i-1的情况下都可以抢劫i+1。
算法:
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]);
int n[] = new int[nums.length];
n[0] = nums[0];
n[1]=Math.max(nums[0], nums[1]);
for(int i=2;i<nums.length;i++){
n[i] = Math.max(nums[i]+n[i-2],n[i-1]);
}
return n[nums.length-1];
}