【LeetCode】213. House Robber II

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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

 

House Robber的差异在于,nums[0]和nums[n-1]不能同时包含,

因此等同于nums[0...n-2]和nums[1...n-1]两者间取较大值。

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.empty())
            return 0;
        if(nums.size() == 1)
            return nums[0];
        vector<int> nums1(nums);
        vector<int> nums2(nums);
        nums1.erase(nums1.begin());
        nums2.pop_back();
        return max(originRob(nums1), originRob(nums2));
    }
    int originRob(vector<int>& nums)
    {
        if(nums.empty())
            return 0;
        int prev2 = 0;
        int prev1 = nums[0];
        for(int i = 1; i < nums.size(); i ++)
        {
            int cur = max(prev2+nums[i], prev1);
            prev2 = prev1;
            prev1 = cur;
        }
        return prev1;
    }
};

posted @ 2015-07-03 17:22  陆草纯  阅读(342)  评论(0编辑  收藏  举报