For each prefix, compare skipping the current house with taking it after the last compatible prefix.
Taking house 3 excludes house 2 and reuses only the earlier optimum
Read it this way:For values (2,7,9,3), skipping house 3 keeps 11. Taking it adds 3 only to the earlier optimum 7, giving 10. Can taking house three add its value to the eleven that already includes neighboring house two?
Sources and provenance
Full interview answer 17 min read
Choose nonadjacent houses along a street to maximize the total value collected.
Problem
Input. An integer list nums giving house values in linear street order.
Output. Return the largest sum over selections containing no two adjacent positions.
Rules. The first and last houses are not neighbors unless they are consecutive in the list.
Selecting no houses is allowed, so empty and all-negative inputs return zero.
Return only the total, not the selected indices. Preserve the input.
Example.[2, 7, 9, 3, 1] returns 12, achieved by indices [0, 2, 4].
Taking 7 and 9 together is forbidden because their positions are adjacent.
Picture
At index 3, taking value 3 excludes index 2.
It can extend the best prefix through index 1, not the immediately preceding prefix.
Reference drawing
Taking house 3 excludes house 2 and reuses only the earlier optimum
Derivation
The take branch stops its reusable prefix two houses back. The skip branch keeps eleven. Their maximum is eleven, without using adjacent houses.
Read it this way:For values (2,7,9,3), skipping house 3 keeps 11. Taking it adds 3 only to the earlier optimum 7, giving 10. Can taking house three add its value to the eleven that already includes neighboring house two?
These cases are exhaustive: a selection either contains the current position or does not.
Neither saved prefix optimum must select its last position.
Taking the current value after the two-back optimum is compatible; skipping preserves the one-back optimum.
Problem trace
Read both old prefix optima before committing the better skip or compatible take
Input and goalFind the most money that can be taken without choosing neighboring houses.
Initialize before house 0For money [2, 7, 9, 3, 1], both saved prefix answers start at zero.
Items lie in a line, adjacent choices conflict, and the objective asks for a maximum total rather than the exact chosen sequence.
Keep true
Before house i, one_house_back is the optimum for houses through i - 1 and two_houses_back is the optimum through i - 2. Therefore max(one_back, two_back + money[i]) is the complete optimum through i.
Reuse it
When choosing item i only conflicts with a fixed neighborhood, compare the optimum that excludes i with value[i] plus the last compatible optimum. This transfers to weighted independent sets on paths and cooldown scheduling.
For money [2, 7, 9, 3, 1], both saved prefix answers start at zero. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: At house 2, why is the take candidate 2 + 9 rather than 7 + 9?
Problem trace
Read both old prefix optima before committing the better skip or compatible take
Read it this way:Both totals are prefix optima, not promises to select their last houses. Skip preserves the previous optimum; take extends the prefix before the neighbor. Read both old values before shifting. The five prefix results are two, seven, eleven, eleven and twelve. At three, skip keeps eleven; compatible take gives ten. An early shift incorrectly gives fourteen using adjacent houses. Empty and negative-only inputs permit zero. Recovering indices requires history; changing exclusion distance changes the dependency. May taking three extend eleven?
Reference drawing
Problem trace
Read both old prefix optima before committing the better skip or compatible take
Execution trace
Input and goalFind the most money that can be taken without choosing neighboring houses.
Initialize before house 0For money [2, 7, 9, 3, 1], both saved prefix answers start at zero.
Items lie in a line, adjacent choices conflict, and the objective asks for a maximum total rather than the exact chosen sequence.
Keep true
Before house i, one_house_back is the optimum for houses through i - 1 and two_houses_back is the optimum through i - 2. Therefore max(one_back, two_back + money[i]) is the complete optimum through i.
Reuse it
When choosing item i only conflicts with a fixed neighborhood, compare the optimum that excludes i with value[i] plus the last compatible optimum. This transfers to weighted independent sets on paths and cooldown scheduling.
For money [2, 7, 9, 3, 1], both saved prefix answers start at zero. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: At house 2, why is the take candidate 2 + 9 rather than 7 + 9?
Read it this way:Both totals are prefix optima, not promises to select their last houses. Skip preserves the previous optimum; take extends the prefix before the neighbor. Read both old values before shifting. The five prefix results are two, seven, eleven, eleven and twelve. At three, skip keeps eleven; compatible take gives ten. An early shift incorrectly gives fourteen using adjacent houses. Empty and negative-only inputs permit zero. Recovering indices requires history; changing exclusion distance changes the dependency. May taking three extend eleven?
After each value, the prefix optima are 2,7,11,11,12.
Compute current before shifting either dependency.
Code
def house_robber(nums: list[int]) -> int: two_houses_back = 0 one_house_back = 0 for money in nums: current = max(one_house_back, two_houses_back + money) two_houses_back, one_house_back = one_house_back, current return one_house_back
At value 9, taking gives 2+9=11, beating 7.
At value 3, skipping keeps 11, beating 7+3=10.
At value 1, taking gives 11+1=12.
The displayed indices are a checked witness, not state retained by this function.
There are O(n) scalar updates and O(1) scalar slots, excluding input and integer-size costs.
Greedily choosing a locally larger value does not compare the required compatible prefix optima.
An arbitrary conflict graph does not share this line-prefix guarantee.
Change the Endpoint Conflict
New task: First and last positions also conflict.
Picture and change: At least one endpoint must be excluded.
Compare the line without the last position against the line without the first.
Handle a single position separately.
def circular_robber(nums): if not nums: return 0 if len(nums) == 1: return max(0, nums[0]) return max(house_robber(nums[:-1]), house_robber(nums[1:]))
Check:[2,3,2] returns 3; its two endpoint values cannot be combined.
[-1] returns 0.
Python slices add O(n) storage despite each line computation’s two saved scalars.
Use when: Only endpoint compatibility changes.
Change the Required Output
New task: Return the total and selected indices.
Picture and change: Retain every prefix optimum, then walk backward.
Skip on ties; otherwise take this index and jump over its excluded neighbor.
def robber_with_indices(nums): best = [0] * (len(nums) + 1) for index, value in enumerate(nums, 1): compatible = best[index - 2] if index >= 2 else 0 best[index] = max(best[index - 1], value + compatible) chosen, index = [], len(nums) while index > 0: if best[index] == best[index - 1]: index -= 1 else: chosen.append(index - 1) index -= 2 return best[-1], chosen[::-1]
Check:[2,7,9,3,1] returns (12,[0,2,4]); [0,0] returns (0,[]).
Selected values must sum to the reported optimum, with no adjacent indices.
This reconstruction retains O(n) table slots plus its output.
Several witnesses can be optimal; the tie policy selects one deterministically.
Use when: The decision must be recovered, not only its value.
Transfer Check
What changes if selecting index i excludes the preceding three positions?
Answer
The take branch needs the optimum through i-4.
The skip branch still uses the preceding prefix optimum.
The compatibility horizon and retained state must expand.