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 rob(vector<int>& nums) {
        int n = nums.size();
        if (n < 1)
        {   
            return 0;
        }
        if (n == 1)
        {
            return nums[0];
        }

        int result = 0;
        int buf[n];
        int maxTable[n];
        //选中第一个的情况
        buf[0] = nums[0];
        maxTable[0] = nums[0];
        buf[1] = nums[1];
        maxTable[1] = nums[0];

        for (int i = 2; i < n-1; i++)
        {
            buf[i] = maxTable[i-2] + nums[i];
            maxTable[i] = max(buf[i], maxTable[i-1]);
        }

        result = maxTable[n-2];
    
        //不选中第一个的情况
        buf[0] = 0;
        maxTable[0] = 0;
        buf[1] = nums[1];
        maxTable[1] = nums[1];
    
        for (int i = 2; i < n; i++)
        {
            buf[i] = maxTable[i-2] + nums[i];
            maxTable[i] = max(buf[i], maxTable[i-1]);
        }

        if (maxTable[n-1] > result)
        {
            result = maxTable[n-1];
        }

        return result;
    }
};


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