Algorithms · Visualized

DP: House Robber

Dynamic Programming

Break problems into overlapping subproblems and store answers.

A robber wants to maximize stolen money from a row of houses, but can't rob two adjacent houses (triggers an alarm). Time: O(n) average, O(n) worst; space: O(n), reducible to O(1).

Big-O: The most-asked interview category — 35 classics here.

House Robber

Dynamic Programming

A robber wants to maximize stolen money from a row of houses, but can't rob two adjacent houses (triggers an alarm). dp[i] represents the maximum money obtainable considering houses up to index i, choosing at each house whether robbing it (skip the previous house) beats skipping it (keep the best from before).

How House Robber Works

  1. Define dp[i] as the maximum money obtainable from the first i+1 houses. Base cases: dp[0] = houses[0], dp[1] = max(houses[0], houses[1]).
  2. For each house i from 2 onward, decide between two choices: rob this house (add its value to dp[i-2], since house i-1 must be skipped) or skip this house (keep dp[i-1] unchanged).
  3. Set dp[i] to the maximum of these two choices.
  4. Continue through all houses.
  5. Return dp[n-1] (the last computed value) as the maximum possible loot.

House Robber Worked Example

Input: [2, 7, 9, 3, 1]

dp[0]=2, dp[1]=max(2,7)=7. dp[2]=max(dp[1], dp[0]+9)=max(7,11)=11. dp[3]=max(dp[2], dp[1]+3)=max(11,10)=11. dp[4]=max(dp[3], dp[2]+1)=max(11,12)=12. Maximum loot: 12 (rob houses at indices 0,2,4: 2+9+1=12).

DP: House RobberO(n)
Max loot without robbing adjacent houses.
2
0
7
1
9
2
3
3
1
4
01
dp27
Step 1 / 6
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
House Robber: dp[i] = max loot up to house i without robbing adjacent houses.
Python · Dynamic Programming Algorithms in Code
def house_robber(nums):
    prev2 = prev1 = 0
    for v in nums:
        prev2, prev1 = prev1, max(prev1, prev2 + v)
    return prev1

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

House Robber Time & Space Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(n), reducible to O(1)

When to Use House Robber

  • The foundational 'no two adjacent choices' DP pattern, used in scheduling non-adjacent tasks and resource selection problems with adjacency constraints.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.