Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — 1-D Dynamic Programming

House Robber

MEDIUM✓ CHIP-TIMEDLC #198 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Houses stand in a row, each holding a set haul, and robbing two adjacent houses trips the alarm. Plan the non-adjacent picks that maximize total takings.

Houses stand in a single row, each holding a fixed amount of cash. Robbing any two houses that are directly next to each other trips a connected alarm system, so adjacent picks are off the table.

The task is to choose a subset of houses, no two adjacent, whose total haul is as large as possible. Skipping houses is free — the only cost is the constraint on which pairs can't both be taken.

The answer is that single maximum total, not the list of which houses were chosen.

  • house count can run into the low thousands
  • each house's haul is a non-negative integer
  • no two robbed houses may be adjacent in the row
  • answer is the maximum total haul, not the chosen houses
EX 01
nums = [5]
→ 5
single house, minimum size
EX 02
nums = [3, 10]
→ 10
two houses, take the bigger
EX 03
nums = [2, 7, 9, 3, 1]
→ 12
classic alternating pick

The hintstake only what you need

HINT 1 THE NUDGE

At each house you either skip it or take it — but taking it locks out the one right before. What does the best plan up to a house actually depend on?

HINT 2 THE STRUCTURE

The best haul through house i is either the best haul that stops before i (skip this house), or this house's value plus the best haul that stopped two houses back (take it).

HINT 3 ONE STEP FROM THE ANSWER

Carry two running totals forward — best haul ending one house back and best haul ending two houses back — and at each new house take the larger of skipping or taking plus that second total.

Coach's boardthe pattern, step by step

THE ALTERNATING HAULPATTERN · ROLLING TWO-STATE DPnums = [2, 7, 9, 3, 1]
2
7
9
3
1
BEST HAUL THROUGH HOUSE
— empty —
STEP 1

No houses robbed yet — both rolling totals, one and two houses back, start at zero.

STEP 1 / 7 · ← → WORK TOO

The splitstwo paces, two languages

grind/house-robber.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def rob(self, nums: List[int]) -> int:
        prev2, prev1 = 0, 0                      # best haul ending two back, one back
        for x in nums:
            prev2, prev1 = prev1, max(prev1, prev2 + x)
        return prev1
TIME O(N)SPACE O(1)PYTHON · RACE PACE · 6 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED