« Back

House Robber

LeetCode

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.

Initial attempt

Time spent: 22m | Runtime: 5.25% | Memory: 20.03%

Solution

max_rob[i] = max(max_rob[i - 1], max_rob[i - 2] + nums[i])

Cleaned up code

Time spent: 5m | Runtime: 20.59% | Memory: 20.03%

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

Note that tuple assignment makes it a lot easier to manage prev and current reassignment.