当前位置:网站首页>Leetcode refers to offer II 089 House theft

Leetcode refers to offer II 089 House theft

2022-06-24 04:11:00 freesan44

subject

A professional thief , Plan to steal houses along the street . There is a certain amount of cash in every room , The only constraint on thieves' theft is that adjacent houses are equipped with interconnected anti-theft systems , If two adjacent houses are broken into by thieves on the same night , The system will automatically alarm .

Given an array of non negative integers representing the storage amount of each house nums , Please calculate   Without triggering the alarm , The maximum amount that can be stolen overnight .

 Example  1:

 Input :nums = [1,2,3,1]
 Output :4
 explain : Steal  1  House No  ( amount of money  = 1) , And then steal  3  House No  ( amount of money  = 3).
      Maximum amount stolen  = 1 + 3 = 4 .
 Example  2:

 Input :nums = [2,7,9,3,1]
 Output :12
 explain : Steal  1  House No  ( amount of money  = 2),  Steal  3  House No  ( amount of money  = 9), Then steal  5  House No  ( amount of money  = 1).
      Maximum amount stolen  = 2 + 9 + 1 = 12 .

Tips :

1 <= nums.length <= 100

0 <= numsi <= 400

Their thinking

class Solution:
    def rob(self, nums: [int]) -> int:
        dp = [0]*len(nums)
        #  The boundary conditions 
        if len(nums) == 1:
            return nums[0]
        elif len(nums) == 2:
            return max(nums[0],nums[1])
        dp[0] = nums[0]
        dp[1] = max(nums[0],nums[1])
        for i in range(2, len(nums)):
            dp[i] = max(dp[i-2]+nums[i],dp[i-1])
        # print(dp)
        return dp[-1]
if __name__ == "__main__":
    nums = [2,7,9,3,1]
    nums = [1, 2, 3, 1]
    nums = [2,1,1,2]
    ret = Solution().rob(nums)
    print(ret)
原网站

版权声明
本文为[freesan44]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/09/20210910184020053x.html