SDE & MLE Prep

198. House Robber

Problem

nums[i] is the money in house i along a street. Robbing two adjacent houses alerts the police. Return the most money you can rob.

Example: [2,7,9,3,1] → 12 (2 + 9 + 1)

At each house: skip it (dp[i−1]) or rob it (dp[i−2] + nums[i]).

nums  2  7  9  3  1
dp    2  7 11 11 12

Complexity: O(n) time, O(1) space.

class Solution:
    def rob(self, nums: List[int]) -> int:
        prev, cur = 0, 0
        for x in nums:
            prev, cur = cur, max(cur, prev + x)
        return cur