您的位置:首页 > 其它

LeetCode 213. House Robber II

2016-06-25 21:24 218 查看
Problem: https://leetcode.com/problems/house-robber-ii/

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.

Thought:

  Uses the code in House-robber, chooce the larger one between num[0] to num[n - 2] and num[1] to num[n - 1]

Code C++:

class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size()==0)
return 0;
else if (nums.size() == 1)
return nums[0];

int n1 = 0,n2 = nums[0];
for (int i = 1; i < nums.size() - 1; i++) {
int temp = n1;
n1 = n2;
n2 = max(temp + nums[i], n2);
}
int pre = n2;

n1 = 0,n2 = nums[1];
for (int i = 2; i < nums.size(); i++) {
int temp = n1;
n1 = n2;
n2 = max(temp + nums[i], n2);
}
int lat = n2;

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