Python3 achieve loot problem

Python3 achieve loot problem

Original title https://leetcode-cn.com/problems/house-robber/

You are a professional thief to steal street plan of the house. Each room are in possession of some cash, the only constraints affecting steal your neighbor's house is equipped with anti-theft system communicate with each other, if two adjacent houses on the same night, thieves broke into the system will automatically alarm .
Given a representative from each non-negative integer array of Housing storage amount calculated in case you do not touch the alarm device, can steal the maximum amount to.

Example 1:

输入: [1,2,3,1]
输出: 4
解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
     偷窃到的最高金额 = 1 + 3 = 4 。

Example 2:

输入: [2,7,9,3,1]
输出: 12
解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
     偷窃到的最高金额 = 2 + 9 + 1 = 12 。

Problem solving:

class Solution:
    def rob(self, nums: List[int]) -> int:
        n = len(nums)
        if n == 0:
            return 0
        if n == 1:
            return nums[0]
        if n == 2:
            return max(nums[0], nums[1])
        e0 = 0
        e1 = nums[0]
        e2 = max(nums[0], nums[1]) #动态规划思路,但是只需要3个中间值
        for i in range(3, n + 1):
            e0, e1, e2 = e1, e2, max(nums[i-1] + e1, nums[i-2] + e0)
        return e2
Published 24 original articles · won praise 0 · Views 417

Guess you like

Origin blog.csdn.net/qq_18138105/article/details/105166013