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]);
if(nums.length==3) return Math.max(nums[0],Math.max(nums[1],nums[2]));
return Math.max(helper(Arrays.copyOfRange(nums,0,nums.length-1)),helper(Arrays.copyOfRange(nums,1,nums.length)));
}
public int helper(int[] nums){
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-2]+nums[i],dp[i-1]);
}
return dp[nums.length-1];
}
}
这个代码初始值要多判断很多步,下面来一个简练的:
public class Solution {
public int rob(int[] nums) {
if(nums.length==0) return 0;
if(nums.length==1) return nums[0];
return Math.max(helper(nums,0,nums.length-2),helper(nums,1,nums.length-1));
}
public int helper(int[] nums,int start,int end){
int include = 0;
int exclude = 0;
for(int j=start;j<=end;j++){
int i=include,e=exclude;
include = e+nums[j];
exclude = Math.max(i,e);
}
return Math.max(include,exclude);
}
}