[leetcode 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.

所有邻居围城一个圈,作为小偷的你要尽可能偷最多的钱,而不被警察发现,如果偷相邻的邻家,就会报警

有N个邻居,因为围成一个圈,所以第一户和最后一户相邻,只要求得1~N和2~N-1住户偷得钱的最大值就好

使用一个类标记到第i个住户时的最大值,并表明要不要偷这一户人家

AC代码:

class Temp{
public :
    int value;
    int number;
};

class Solution {
public:
    int cal(vector<int> &nums,int start,int stop)
    {
        Temp count[stop-start+1];
        count[0].value=nums[start];
        count[0].number=start;
        if(nums[start+1]>nums[start])
        {
            count[1].value=nums[start+1];
            count[1].number=start+1;
        }
        else
        {
            count[1].value=nums[start];
            count[1].number=start;
        }

        for(int i=start+2;i<=stop;++i)
        {
            if(count[i-start-1].number!=i-1)
            {
                count[i-start].value=count[i-start-1].value+nums[i];
                count[i-start].number=i;
            }
            else
            {
                if(nums[i]+count[i-start-2].value>count[i-start-1].value)
                {
                    count[i-start].value=nums[i]+count[i-start-2].value;
                    count[i-start].number=i;
                }
                else
                {
                    count[i-start].value=count[i-start-1].value;
                    count[i-start].number=i-start-1;
                }
            }
        }
        return count[stop-start].value;

    }
    int rob(vector<int>& nums) {
        int sum=nums.size();
        if(sum==0)
            return 0;
        if(sum==1)
            return nums[0];
        if(sum==2)
            return nums[0]>nums[1]?nums[0]:nums[1];
        int x=cal(nums,0,sum-2);
        int y=cal(nums,1,sum-1);
        return x>y?x:y;
    }
};

其他Leetcode题目AC代码:https://github.com/PoughER/leetcode

你可能感兴趣的:(LeetCode,C++,house,II,213,Robber)