问题描述
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有什么关系
想法
- 显然,此问题的解不大于House Robber的解
- 如果没有抢劫最后一个house,则可以抢劫第1个house,如果抢劫了最后一个house,则第一个house不能劫。即无论如何此问题的解都在[0::n-1](抢劫了第一个)和[1::n](没有抢劫第一个)中的一个最大的(PS:如果既没有抢劫第一个也没有抢劫最后一个,那么这个解[0::n-1]和[1::n]都有包含)。
代码
class Solution {
public:
int help(vector<int> &a, int start, int end){
int no = 0, yes = 0;
for(int i = start; i < end; i++){
int temp = yes;
yes = max(yes, no + a[i]);
no = max(no, temp);
}
return max(yes,no);
}
int rob(vector<int>& nums) {
int n = nums.size();
if(n == 0)
return 0;
if(n == 1)
return nums[0];
return max(help(nums,0,n - 1), help(nums,1,n));
}
};