213. 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.
题目大意
在一个循环数组中,找出一个不存在相邻元素的组合,使它的和最大。
我的解答
//考虑一个长为n的数组,0和n-1不能同时存在,则分为两组讨论,0~n-2和1~n-1
class Solution {
public:
int rob(vector<int>& nums) {
if(nums.size() < 2) return nums.size()? nums[0]:0;
return max(robber(nums,0,nums.size()-2),robber(nums,1,nums.size()-1));
}
private:
int robber(vector<int>& nums, int l, int r) {
int pre = 0, cur = 0;
for (int i = l; i <= r; i++) {
int temp = max(pre + nums[i], cur);
pre = cur;
cur = temp;
}
return cur;
}
};