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.

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

Subscribe to see which companies asked this question


刚开始看到这个题不知道怎么判断0和n-1个数的情况,看别的文章中说只要两次调用House Robber就好了,但是感觉还是有点别扭,不知道还有没有其他更好的解答。

class Solution {
public:
    int rob(vector<int>& nums) {
        int n=nums.size();
        if(n==0)
            return 0;
        if(n==1)
            return nums[0];
        if(n==2)
            return max(nums[0],nums[1]);
        return max(rob(nums,0,n-1),rob(nums,1,n));
        
    }

//下面就是House Robber的解答,用a表示第i-2次,b表示i-1次,省去了开一个数组保存的麻烦。
    int rob(vector<int>&nums, int start, int end)
    {
        int a=0,b=0;
        for(int i=start;i<end;i++)
        {
            int m=max(b,a+nums[i]);
            a=b;
            b=m;
        }
        return b;
    }
};

阅读更多
文章标签: leetcode
个人分类: leetcode
上一篇记录一次大规模linux系统root密码撞库的经历
下一篇337. House Robber III
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭