第十五周leetcode题

本文探讨了一种算法问题——专业窃贼计划沿街抢劫,但为了避免触发报警系统,不能连续抢劫相邻房屋。通过动态规划求解最大抢劫数额。

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

Description:

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

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.


小偷偷东西,在不能偷相邻两户人家的前提下尽可能地多偷东西。设在第i户人家时拥有的钱为mon[i],第i户人家的钱为nums[i],在第i户人家处,因为不能连续偷两户,因此如果偷的话获得的钱为在第i-2户人家时拥有的钱+第i户的钱(第i-1户不能偷),如果不偷的话就为在第i-1户人家时拥有的钱。i=0的时候显然必须偷(不偷的话会比偷少),i=1时则要与mon[0]比较,如果nums[1]>nums[0]的话则要偷,否则不偷(只有两家的话明显要偷有钱的)。i>=2时便可以用这条规则计算,即mon[i]=max(mon[i-2]+nums[i], mon[i-1])。

代码如下:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值