题目描述:
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
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.
先写上House Robber.的解答吧,太简单了,就全部一起写了:
public class Solution {
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[] dp=new int[nums.length];
dp[0]=nums[0];
dp[1]=Math.max(nums[0], nums[1]);
for(int i=2;i<nums.length;i++){
dp[i]=Math.max(dp[i-1], dp[i-2]+nums[i]);
}
return dp[nums.length-1];
}
}
而本题不允许第一个和最后一个一起被偷,那么我们可以假设小偷从nums[0],偷到nums[n-2],然后又从nums[1]偷到nums[n-1],这样就可以使得nums[0]和nums[n-1]永远不会一起被偷了,然后比较他们的最大值,就是被偷的最大值。
代码如下:
public class Solution {
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(Math.max(nums[0], nums[1]),nums[2]);
int[] dp1=new int[nums.length-1];
dp1[0]=nums[0];
dp1[1]=Math.max(nums[0], nums[1]);
for(int i=2;i<nums.length-1;i++){
dp1[i]=Math.max(dp1[i-1], dp1[i-2]+nums[i]);
}
int[] dp2=new int[nums.length-1];
dp2[0]=nums[1];
dp2[1]=Math.max(nums[1], nums[2]);
for(int i=3;i<nums.length;i++){
dp2[i-1]=Math.max(dp2[i-2], dp2[i-3]+nums[i]);
}
return Math.max(dp1[dp1.length-1], dp2[dp2.length-1]);
}
}