标签:
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.
这道题就是在上一题的基础上加了一个条件,变成了环,所以如果抢了第一家,就不能抢最后一家。所以我们可以分别计算抢了从第二家到最后一家与抢从第一家到倒数第二家的最大值,取两个值中更大的那个就是结果。
/**
* 给定一个数组表示其对应的财富,小偷不能连续偷两家,求小偷的最大利益。注意第最后一家的下一个是第一家。
* @date 20160510
*/
public int rob(int[] nums) {
int len = nums.length;
if(len == 0){
return 0;
}else{
if(len == 1){
return nums[0];
}else{
int t1 = robSub(nums,0,len-2);//包含首个不含末个
int t2 = robSub(nums,1,len-1);//不含首个包含末个
return t1>t2?t1:t2;
}
}
}
/**
* 计算子数组[start,end]可获得的最大利益。
*/
public int robSub(int[] nums,int start,int end) {
int len = end-start+1;
if(len == 0){
return 0;
}else{
if(len == 1){
return nums[start];
}else{
int t1 =nums[start];//以nums[i-1]结尾的最大值
int t2 =0;//不以nums[i-1]结尾的最大值
for(int i=start+1;i<=end;i++){
int temp1 = t1;
int temp2 = t2;
t1 = temp2+nums[i];//以nums[i]结尾的最大值
t2 = Math.max(temp1, temp2);//不以nums[i]结尾的最大值
}
return t1>t2?t1:t2;
}
}
}标签:
原文地址:http://blog.csdn.net/u010339647/article/details/51361918