House Robber

一、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.

分析:实际上是求一个由非负整数组成的数组,不能同时取相邻两个的最大和。容易想到动态规划, 设dp[i] 当循环到第i 个元素时,此时的最大值包括两种情况:1)不抢当前的房子,那么dp[i] = dp[i-1], 如果要抢当前的房子,那么它上一个就不能抢。所以此时dp[i] = dp[i-2] + nums[i]

由此可以看到,当前的结果实际上只与上次和上上次的结果有关。所以可以维护两个变量a 和 b分别代表dp[i-2] 和dp[i-1]. a 初始化为nums[0], b 初始化为max[nums[0],nums[1]). 然后从i = 2 开始循环。要注意排除特殊情况

class Solution:
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        if len(nums) == 1:
            return nums[0]
        
        #与当前间隔一个的计算结果
        a = nums[0]
        #i-1时的最大值
        b = max(nums[0],nums[1])
        
        for i in range(2,len(nums)):
            tmp = b
            b = max(a + nums[i], b)
            a = tmp

        return b

如果从index = 0 开始循环,就将特殊情况包括了

#与当前间隔一个的计算结果
        a = 0
        #i-1时的最大值
        b = 0
        
        for i in range(0,len(nums)):
            tmp = b
            b = max(a + nums[i], b)
            a = tmp
        return b

  

但是后一种的时间比前一种慢,,,有小伙伴能解答一下吗

总结:动态规划的步骤:1)定义变量;2)找递推关系 3)初始化变量

二、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 

分析:变成环以后,第一个房子和最后一个房子只能选一个,所以分为两种情况:包括第一个房子在内求最大值;包括最后一个房子在内求最大值,然后两者中再取最大即可。

class Solution:
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 1:
                return nums[0]
            
        def robber(nums):
            a = 0
            b = 0
            for i in range(0,len(nums)):
                tmp = b
                b = max(a + nums[i], b)
                a = tmp
            return b
     
        return max(robber(nums[0:-1]),robber(nums[1:]))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值