LeetCode 213. House Robber II

213. House Robber II

Description
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.

Analysis
这道题的意思就是求给出一系列n个住户中家中所有的金额,而我是小偷,我要计算出能偷的最大的金额。
限制就是我不能连续两家进行偷盗, 以及第n户和第1户不能一起进行偷窃,其实就是形成环了。
我的做法很简单,就是设置一个结果数组res[n],来显示要可以偷窃的金额。
res[i]就是在第i个用户时能偷窃的最大金额。
我的做法就是每一次都更新res,即当前res[i]其实是第i-1个与第i-2个加上当前用户所有金额的值,是这两者之间的较大值。
我们计算从第一个到倒数第二个的最大res值,以及从第二个到最后一个n的最大res值。
将两个值进行比较,较大值为结果。

Code


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

        int len = nums.size();
        int res[len];
        res[0] = nums[0];
        res[1] = max(nums[0],nums[1]);

        for(int i = 2;i<len;++i){
            res[i] = max(res[i-1] , res[i-2] + nums[i]);
        }
        int a = res[len-2];

        res[1] = nums[1];
        //res[2] = max(nums[1],nums[2]);
        for(int i = 2 ; i <len;++i){
            if(i == 2) res[i] = max(nums[1],nums[2]);
            else res[i] = max(res[i-1],res[i-2]+nums[i]);
        }
        return max(a,res[len-1]);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值