Leetcode-198. House Robber家強盗(DP)


タイトル
あなたはプロの泥棒で、街沿いの家を盗む計画です.各部屋には一定の現金が隠されていて、あなたの窃盗に影響する唯一の制約要素は隣接する家に相互に連通する防犯システムが設置されていることです.もし2つの隣接する家が同じ夜に泥棒に侵入されたら、システムは自動的に警察に通報します.各家屋の保管金額を表す非負の整数配列を指定し、警報装置に触れずに盗むことができる最高金額を計算します.リンク:https://leetcode.com/problems/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.
Example:
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.
構想とコード
DP
  • ans:現在までに得られた最も多いお金
  • ans = max(num + temp, one)
  • num+temp:強盗当日と仮定すると、2日前に得られる最も多いお金+今日の
  • one:前日に得られた最も多かったお金
  • class Solution:
        def rob(self, nums: List[int]) -> int:
            one = 0
            two = 0
            for num in nums:
                temp = one
                one = two
                two = max(num + temp, one)
            return two
    

    複雑さ
    T = O ( n ) O(n) O(n) S = O ( 1 ) O(1) O(1)