您的位置:首页 > 其它

House Robber II

2015-08-19 15:03 351 查看
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(/article/8667869.html)的区别是,整个数组的第一个数字和第二个数字是相连的,选择了第一个数字就不能选择最后一个数字,情况就变成第一个数字要么被选择,要么不被选择。 如果第一个数字未被选择,那么就应该求从1到n-1的中所能获得money的最大值temp1,如果第一个数字被选择了,那么就应该求从0到n-2中所能获得money的最大值temp2,返回temp1和temp2中较大的一个即可。

public class Solution {
public int rob(int[] nums) {
int n=nums.length;
if(n==0) return 0;
int best0=0;
int best1=0;
if(n==1) return nums[0];
for(int i=1;i<n;i++)
{
int temp=best0;
best0=best0>best1 ? best0 :best1;
best1=temp+nums[i];
}
int temp1= Math.max(best0,best1);

best0=0;
best1=0;
for(int i=0;i<n-1;i++)
{
int temp=best0;
best0=best0>best1 ? best0 :best1;
best1=temp+nums[i];
}
int temp2=Math.max(best0,best1);
return Math.max(temp1,temp2);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: