198. House Robber

Must take current house, no memory optimization

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        
        if len(nums) <= 2:
            return max(nums)
        
        dp = [0] * len(nums)
        # if len(nums) == 3: # either len(nums) == 3 or > 3, this dp[2] should be calculated.
        # dp[2] = max(nums[1], nums[0] + nums[2])  # 需要确定清楚 dp 的表示含义,既然我们定义 dp 为一定取当前 i 时的 max money,那么 dp[2] 只能为 nums[0] + nums[2]
        dp[0] = nums[0]
        dp[1] = nums[1]
        dp[2] = nums[0] + nums[2]
        
        for i in range(3, len(nums)):
            dp[i] = nums[i] + max(dp[i - 2], dp[i - 3])
            
        return max(dp[-1], dp[-2])

Must take current house, with memory optimization:

Don't have to take current house, with memory optimization:

Last updated