Python easy to understand solution


  • 0
    H

    dp[i] contains max amount that robber can take from house i
    At each index, we check for the max amount from 0 to index - 1, since we can't take the adjacent house's money
    and we add the current amount to the max amount

    class Solution(object):
        def rob(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if not nums: return 0
            
            dp = [0] * len(nums)
            for i in range(len(nums)):
                if i-1 > 0:
                    dp[i] = nums[i] + max(dp[:i-1])
                else:
                    dp[i] = nums[i]
            return max(dp)
    

    O(n) time and space complexity


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.