LeetCode 213. House Robber II

探讨了一个贼如何在环形排列的房屋中进行抢劫,以最大化收益同时避免触发警报的问题。通过将问题分解为两部分并使用动态规划来解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Since, the houses are surrounded like a circle. If we rob index 0,  we can't rob index size - 1.

Take an example for break:

[4, 2, 3, 13, 8, 22]:

if I start robbing  4,  the max would be 4 + 13 -> 17.

If I dont start robbing 4, the max would be 2+13+22 -> 37.

I thus separate the robbing into two cases:

1) start robbing at index 0, stop at size - 2;

2) start robbing at index 1, stop at size - 1.

   int rob(vector<int>& nums) {
        if(nums.size() == 0) return 0;
        if(nums.size() == 1) return nums[0];
        if(nums.size() == 2) return max(nums[0], nums[1]);
        vector<int> maxWithFirst(nums.size(), 0);
        vector<int> maxWithLast(nums.size(), 0);
        maxWithFirst[0] = nums[0];
        maxWithFirst[1] = max(nums[0], nums[1]);
        
        maxWithLast[1] = nums[1];
        maxWithLast[2] = max(nums[1], nums[2]);
        
        for(int i = 2; i < nums.size() - 1; ++i) {
            maxWithFirst[i] = max(nums[i] + maxWithFirst[i-2], maxWithFirst[i-1]);
        }
        
        for(int j = 3; j < nums.size(); ++j)
            maxWithLast[j] = max(nums[j] + maxWithLast[j-2], maxWithLast[j-1]);
            
        int n = nums.size();
        return max(maxWithFirst[n - 2], maxWithLast[n - 1]);
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值