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 ProgrammingA 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
- 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]).
- 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).
- Set dp[i] to the maximum of these two choices.
- Continue through all houses.
- 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).
| 0 | 1 | |
|---|---|---|
| dp | 2 | 7 |
def house_robber(nums):
prev2 = prev1 = 0
for v in nums:
prev2, prev1 = prev1, max(prev1, prev2 + v)
return prev1Behind 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
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
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.