leetcode 198. House Robber

wonderful world·2021년 9월 17일
0

leetcode

목록 보기
1/21

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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Example 1

Input: nums = [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.

Recursive solution

class Solution:
    def rob(self, nums: List[int]) -> int: 
        def f0(nums):
            if nums==[]:return 0
            ret = []
            #take head
            ret = [nums[0] + f0(nums[2:])]
            #skip head then take next
            if len(nums)>1:
                ret +=[nums[1] + f0(nums[3:])]
            return max(ret)
        
        return f0(nums)

Dynamic programming solution

class Solution:
    def rob(self, nums: List[int]) -> int: 
        # dynamic programming
        def f(nums):
            count = len(nums)
            dp = [0 for _ in range(count)]
            for i in range(count):
                dp2 = dp[i-2] if i >= 2 else 0
                dp1 = dp[i-1] if i >= 1 else 0
                v = nums[i]
                # case 1. take current value + accumulated value up to i-2. 
                acc0 = dp2 + v
                
                # case 2. skip current value. just assigned to accumulated value up to i-1.
                acc1 = dp1
                dp[i] = max(acc0, acc1)
                
            return dp[count-1]
        return f(nums)
profile
hello wirld

0개의 댓글