Take or skip, two rolling cells
At house i you either skip it (prev) or take it plus the best from two houses back (prev2 + nums[i]). Adjacent houses cannot both be robbed.
dp[i] = max(dp[i-1], dp[i-2] + nums[i]). Two variables replace the array.
Algorithm
prev2 = 0,prev = 0.- For each house:
prev2, prev = prev, max(prev, prev2 + x). - Return
prev.
- Time
- O(n)
- Space
- O(1)
class Solution: def rob(self, nums: list[int]) -> int: prev2 = prev = 0 for x in nums: prev2, prev = prev, max(prev, prev2 + x) return prev