题目:
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.
思路:因为相邻的两个房间被偷的时候,会触发警报,所以要求不相邻的组合的最大值。
给定一个数组nums,考虑动态规划Dynamic Programming来解,我们维护一个数组dp大小与nums相同,递推公式为dp[i] = max(dp[i-2]+nums[i],dp[i-1]); 并初始化dp[0] = nums[0],dp[1] = max(nums[0],nums[1]);
具体代码如下:
public class Solution {
public int rob(int[] nums) {
int len = nums.length;
if(len == 0){
return 0;
}
if(len == 1){
return nums[0];
}
int[] dp = new int[len];
dp[0] = nums[0];
dp[1] = Math.max(nums[0],nums[1]);
int i = 2;
while(i < len) {
dp[i] = Math.max(nums[i] + dp[i-2],dp[i-1]);
i++;
}
return dp[len-1];
}
}