Solution 1
class Solution:
def rob(self, nums: List[int]) -> int:
# for house 0, we have to choose: rob or not. If we rob, the max total amount we can get is the max amount at point house -2 + amount in house 0. If not, the max total amount we can get is the max amount at point house -1.Thus, the largest amount is max( amount at house -2 + house 0, amount at house -1)
dp_last, dp_now = 0, 0
for num in nums:
dp_last, dp_now = dp_now, max(dp_last + num, dp_now)
return dp_now
Time complexity is O(n). Space complexity is O(1).