You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
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.
Example 1:
Input: [2,3,2] Output: 3 Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
/* 一个环形数组 不能访问连续相邻两个求最大和
* max(rob[0,n-2], rob[1,n-1])
* dp[i] = max(dp[i-1], dp[i-2]+nums[i]) 可以用两个变量来记录而非一个数组 类似于两个变量优化的斐波那契数列
* temp p2 p1
*
* */
class Solution {
public:
int rob(vector<int>& nums) {
int len=nums.size();
if(len<2) return len==0? 0 : nums[0];
return max(myrob(nums, 0, len-1), myrob(nums, 1, len));
}
int myrob(vector<int> &nums, int l, int r){// rob nums[l,r)
int p1=0, p2=0;
for(int i=l;i<r;i++){
int temp = max(p1+nums[i], p2);
p1 = p2;
p2 = temp;
}
return p2;
}
};