The Runtime Theory
mediumleetcode#dynamic-programming

House Robber

Find the maximum amount robbed from a street where no two adjacent houses can be hit; linear dynamic programming keeps two running totals.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

innums = [1,2,3,1]

out4

innums = [2,7,9,3,1]

out12

Given an array of house values on a straight street, the machine must pick a subset with the maximum total value while never choosing two adjacent houses. This is a classic linear dynamic programming problem where the decision at each house has exactly two options.

The key insight is a local choice that respects the future: at house i, the machine either skips it and keeps the best loot from the previous i-1 houses, or robs it and adds nums[i] to the best loot from the first i-2 houses (the previous house becomes untouchable). The state is just best[i] = max(best[i-1], best[i-2] + nums[i]).

The approach runs in three steps. First, start with two running totals: 0 for "two houses back" and 0 for "one house back". Second, walk the array once, replacing the pair with (previous total, max of robbing or skipping the current house). Third, return the final running total. Time is O(n) and space is O(1), because the recurrence only ever needs the last two states.

The trickiest edge case is the empty or single-house input: with an empty array the machine must return 0, and with one house it must return that house's value without ever indexing a table. The two-variable sliding window handles both naturally since the loop simply never runs.

python
def rob(nums):
    prev, curr = 0, 0
    for n in nums:
        prev, curr = curr, max(curr, prev + n)
    return curr

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.