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.

这题题意给的很有意思,说是抢劫的最多的钱的数目。 实际上是求数组中避免取相邻元素的最大和。

这题定义子状态非常关键,如果只是定义为抢劫数组第i个元素的能得到最大值,则不仅需要扫描一遍数组,还需要不断更新最大值。另外一个定义直接是数组的前i 个元素可以取到的最大和,即不一定包含当前元素,这样也避免再取一次最大值。转换方程为f[i] = max(f[i-1], f[i-2]+nums[i]). f[i-1]也不一定包含nums[i-1]元素,为何只在f[i-2]上加呢。因为如果f[i-1]不包含nums[i-1],则  f[i-1] = f[i-2]。这题可以进行空间优化,只需要保存前面两个状态。

一个是直接取前两个状态,每次计算,交替更新:

代码如下:

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        if len(nums) < 2:
            return nums[0]
        f1 = nums[0]
        f2 = max(nums[0], nums[1])
        for n in nums[2:]:
            res = max(f1 + n, f2)
            f1 = f2
            f2 = res
        return f2

另外一个是利用%2的策略,取一个长度为2的数组。即跟前面几个状态有关,则取几个,后面每次计算取值也是将index%2,代码如下:

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        if  len(nums) < 2:
            return nums[0]
        #f[i]: max money can get when reach A[i]
        res = [nums[0], max(nums[0], nums[1])]
        for i in xrange(2, len(nums)):
            res[i%2] = max(res[(i-2)%2] + nums[i], res[(i-1)%2])
            
        return res[(len(nums)-1)%2]

 

转载于:https://www.cnblogs.com/sherylwang/p/5579696.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值