您的位置:首页 > 其它

LeetCode 213. House Robber II

2016-04-21 07:28 387 查看
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.

Since, the houses are surrounded like a circle. If we rob index 0, we can't rob index size - 1.

Take an example for break:

[4, 2, 3, 13, 8, 22]:

if I start robbing 4, the max would be 4 + 13 -> 17.

If I dont start robbing 4, the max would be 2+13+22 -> 37.

I thus separate the robbing into two cases:

1) start robbing at index 0, stop at size - 2;

2) start robbing at index 1, stop at size - 1.

int rob(vector<int>& nums) {
if(nums.size() == 0) return 0;
if(nums.size() == 1) return nums[0];
if(nums.size() == 2) return max(nums[0], nums[1]);
vector<int> maxWithFirst(nums.size(), 0);
vector<int> maxWithLast(nums.size(), 0);
maxWithFirst[0] = nums[0];
maxWithFirst[1] = max(nums[0], nums[1]);

maxWithLast[1] = nums[1];
maxWithLast[2] = max(nums[1], nums[2]);

for(int i = 2; i < nums.size() - 1; ++i) {
maxWithFirst[i] = max(nums[i] + maxWithFirst[i-2], maxWithFirst[i-1]);
}

for(int j = 3; j < nums.size(); ++j)
maxWithLast[j] = max(nums[j] + maxWithLast[j-2], maxWithLast[j-1]);

int n = nums.size();
return max(maxWithFirst[n - 2], maxWithLast[n - 1]);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: