4.28python Leetcode 213

本文探讨了一道经典的动态规划问题——环形房屋抢劫者II。该问题是LeetCode上的一道编程题,需要找到一种算法,在不触发报警的前提下,计算出能够从一系列环形排列的房屋中抢夺的最大金额。

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

213House Robber II

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, 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.

Example 1:

Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
             because they are adjacent houses.

Example 2:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.


题解:

环形数组,每次只能取不相邻的2个数,求最大和。

动态规划问题。

对于从2开始的每一个房间i,到这个房间为止能偷到的最多的钱

max_money[i] = max( max_money[i-1], max_money[i-1] + nums[i] )

当然,因为是环形数组,因此要考虑第一第二个房间和最后一个房间的关系。

我这里是直接进行了2次dp,第一次考虑如果只取第一个房间的钱,舍弃第二个房间和最后一个房间的钱。

第二次是不取第一个房间的钱,其他正常取。这样就可以覆盖全部的情况了。



class Solution(object):
    def rob(self, nums):
        if nums:
            if(len(nums) == 1):
                return nums[0]
            
            max_money1 = [0 for i in range(len(nums))]
            max_money2 = [0 for i in range(len(nums))]
            max_money1[0] = nums[0]
            max_money1[1] = nums[0]
            max_money2[0] = 0
            max_money2[1] = nums[1]
            
            i = 2
            while i < len(nums) -1:
                max_money1[i] = max(max_money1[i-1], max_money1[i-2] + nums[i])
                i = i+1
            i = 2
            while i < len(nums):
                max_money2[i] = max(max_money2[i-1], max_money2[i-2] + nums[i])
                i = i +1
            
            return max(max_money1[-2], max_money2[-1])
        else:
            return 0
        
        """
        :type nums: List[int]
        :rtype: int
        """


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值