LeetCode----House RobberII

本文探讨了HouseRobberII问题,这是HouseRobber问题的一个扩展版本,涉及到在一个环状排列的房屋中寻找最大的抢劫金额,同时确保不会触动警报。文章提供了详细的动态规划解决方案,并附带了Python实现代码。

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

House Robber II


Note: This is an extension of House Robber.

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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.


分析:

House Robber的升级版,依然是一道简单的动态规划问题。其动态转移方程同上一题。不过有个细节需要思考清楚,这题从线形变成变成了环形,首和尾不能同时选取。假设数组为nums,长度为len,如果选取了第一个元素,那么就等于是从nums[0 -> len - 2]中选择最多的money,即放弃了最后一个元素;同理,如果选择了第二个元素,那么就等于是从nums[1 -> len - 1]中选择最多的money,即放弃了第一个元素。如果还是不好理解,可以在纸上画图理解下。


代码:

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums_len = len(nums)
        if nums_len == 0:
            return 0
        elif nums_len in [1, 2, 3]:
            return max(nums)
        else:
            return max(self.getMaxMoney(nums, 0, nums_len - 2), self.getMaxMoney(nums, 1, nums_len - 1))

    def getMaxMoney(self, nums_l, left, right):
        f = {}  # record the max money
        f[left] = nums_l[left]
        f[left + 1] = nums_l[left] if nums_l[left] > nums_l[left + 1] else nums_l[left + 1]
        for i in range(left + 2, right + 1):
            f[i] = max(f[i - 1], f[i - 2] + nums_l[i])
        return f[right]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值