213. House Robber II

原创 2016年08月31日 15:57:07

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 OJ> (198 / 213) House Robber(I / II)

House Robber My Submissions Question Total Accepted: 45702 Total Submissions: 142460 Difficulty:...

[leetcode 213]House Robber II

Note: This is an extension of House Robber. After robbing those houses on that street, the thief ha...

leetcode - 198,213. House Robber(II) & 91. Decode Ways

算法系列博客之Dynamic Programming 本篇博客将运用动态规划的思想来解决leetcode上198和213号问题 问题描述:198 House RobberYou are a pr...

leetcode 213. House Robber II

After robbing those houses on that street, the thief has found himself a new place for his thievery ...

LeetCode No.213 House Robber II

LeetCode No.213 House Robber II

LeetCode-213. House Robber II

Note: This is an extension of House Robber. After robbing those houses on that street, the thief ha...

LeetCode 213 House Robber II (dp 三种方法 推荐)

LeetCode 213 House Robber II (dp)

Leetcode 213 House Robber II 抢劫最大金额

HouseRobber扩展:抢劫完那条街道上的房子之后,这个贼有找到了实施自己盗窃行动的另一个地点,这样他才不会引来太多注意。这次,这里的搜有房子排成了一个圆圈,这意味着第一个房子和最后一个房子也是挨...

LeetCode#213. House Robber II

213. House Robber II Total Accepted: 23996 Total Submissions: 80010 Difficulty: Medium Note: This i...

LeetCode 213. House Robber II 注意考察环尾和环头交叉处

213. House Robber II After robbing those houses on that street, the thief has found himself a new ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)