213. House Robber II

Note: This is an extension of House Robber.

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.

【思路】由于第一个和最后一个相连,此问题就变成抢了第一个,就不能抢最后一个,即在 从第一个到倒数第二个之间的最大值,和从第二个到最后一个最大值 ,这两个最大值之间选最大的。

class Solution {
public:
    int robSub(vector<int>& nums,int first, int last) {
        int no_rob = 0;
        int rob = 0;
        for(int i = first; i < last; i++)
        {
            int tmp = no_rob;
            no_rob = max(no_rob, rob);
            rob = tmp + nums[i];
        }
        return max(no_rob, rob);
    }
    int rob(vector<int>& nums) {
        int len = nums.size();
        if(len==0) return 0;
        if(len==1) return nums[0];
        
        return max(robSub(nums,0,len-1), robSub(nums,1, len));
    }
};



你可能感兴趣的:(213. House Robber II)