8/23/2020

[LeetCode] 198. House Robber

 Problem : https://leetcode.com/problems/house-robber/

Robber has 2 choices for each house,  steal this house if the previous house is not be stolen or not steal this house.

DP solution

Time Complexity = O ( N )


class Solution:
    def rob(self, nums: List[int]) -> int:
        if not nums:
            return 0
        
        if len(nums) <= 2:
            return max(nums)
        
        steal = [0] * len(nums)
        notSteal = [0] * len(nums)
        
        steal[0] = nums[0]
       
        for i in range(1, len(nums)):
            steal[i] = notSteal[i-1] + nums[i]
            notSteal[i] = max(notSteal[i-1], steal[i-1])
            
        return max(steal[-1], notSteal[-1])

Another DP solution


class Solution:
    def rob(self, nums: List[int]) -> int:
        if not nums:
            return 0
        
        if len(nums) <= 2:
            return max(nums)
        
        dp = [0] * len(nums)
        
        dp[0] = nums[0]
        dp[1] = max(nums[0], nums[1])
        
        for i in range(2, len(nums)):
            # max(not-rob-house-i, rob-house-i)
            dp[i] = max(dp[i-1], dp[i-2] + nums[i])
        
        return dp[-1]

Memorization solution

Time Complexity =  O ( N ).  

class Solution:
    def rob(self, nums: List[int]) -> int:
        
        @lru_cache(maxsize = None)
        def dfs(i, safe):
            if i >= len(nums):
                return 0
            
            s1 = nums[i] + dfs(i+1, False) if safe else 0
            s2 = dfs(i+1, True)
            
            return max(s1, s2)
        
        
        return dfs(0, True)

No comments:

Post a Comment