Leetcode-198-House Robber

本文探讨了一种称为“抢劫者问题”的经典动态规划题目。该问题要求从一系列非负整数中选取不相邻元素以使总和最大化,模拟抢劫者在不能连续抢劫两户的情况下如何计划获取最多财富。

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

题目:

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.

int rob(int* nums, int numsSize) {
    int i;
    if(numsSize == 0) return 0;
    if(numsSize>1 && nums[0]>nums[1]) nums[1] = nums[0];
    for(i = 2; i < numsSize; i ++){
        nums[i] = (nums[i-2]+nums[i]>nums[i-1])?(nums[i-2]+nums[i]):nums[i-1];
    }
    return nums[numsSize-1];
}


解析:

题目的意思是给一串非负数,求不相邻的数字最大和(题目中说不能获取相邻两个房子的金钱)

这是一道动态规划题目,我们设定每个房子的金钱为m(k)

到第k个房子时能获得的最大金钱数为p(k)=max(p(k-2)+m(k), p(k-1))

p(0)=0, p(1) = m(1), p(2) = max(p(0)+m(2), p(1))=max(m(2), m(1))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值