ZhongKuo0228 / study

0 stars 0 forks source link

198. House Robber #117

Open fockspaces opened 10 months ago

fockspaces commented 10 months ago
  1. use dp to maintain "the max amount thief can steal at index i"
  2. initial state: dp[0] -> only can choose nums[0], dp[1] -> either nums[0] or nums[1]
  3. update and get the ans
class Solution:
    def rob(self, nums: List[int]) -> int:
        nums.append(0)
        dp = [0] * (len(nums))
        dp[0] = nums[0]
        dp[1] = max(nums[0], nums[1])
        for i in range(2, len(dp)):
            dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
        return dp.pop()
fockspaces commented 10 months ago

we can smooth dp without extend its length, if comes to one or two nums length, we just return the maximun elements in list

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