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.
思路:本题是一个典型的动态规划题目,设置一个dp[i]记录到第i家时强盗可以抢到的最大钱数。根据题意,可以得出dp的递归式
dp[0]=nums[0],dp[1]=max(nums[0],nums[1])
dp[i]= max(dp[i-2]+nums[i],dp[i-1]);
代码如下(已通过leetcode)
public class Solution {
public int rob(int[] nums) {
int length=nums.length;
if(length==0) return 0;
if(length==1) return nums[0];
if(length==2) return nums[0]>nums[1]?nums[0]:nums[1];
int[] dp=new int[length];
dp[0]=nums[0];
dp[1]=Math.max(nums[0], nums[1]);
for(int i=2;i<length;i++)
dp[i]=Math.max(dp[i-2]+nums[i], dp[i-1]);
return dp[length-1];
}
}