您的位置:首页 > 其它

【LeetCode】213. House Robber II

2016-10-17 15:05 274 查看
题目:

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的扩展。在一个环形数组(即第一个元素与最后一个原始相邻)中取出不相邻的且和最大的数。

可以分两种情况来考虑:(1)不取第一个元素

(2)不取最后一个元素

最后返回两种情况中的最大值。

代码:

class Solution {
public:
int rob(vector<int>& nums) {
int l = nums.size();
if(l == 0)
return 0;
if(l == 1)
return nums[0];
int sum[3];
int max;
for(int i = 0;i<3;i++)
{
sum[i] = 0;
}
for(int i = 0;i<l-1;i++)
{

sum[2] = sum[0]+nums[i];
if(sum[2]<sum[1])
sum[2] = sum[1];
sum[0] = sum[1];
sum[1] = sum[2];
}
max = sum[2];
for(int i = 0;i<3;i++)
{
sum[i] = 0;
}
for(int i = 1;i<l;i++)
{

sum[2] = sum[0]+nums[i];
if(sum[2]<sum[1])
sum[2] = sum[1];
sum[0] = sum[1];
sum[1] =sum[2];
}
if(max<sum[2])
return sum[2];
else return max;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode