House Robber solution explained
House Robber asks for the largest sum you can collect from a list of non-negative numbers when no two chosen positions may sit next to each other. The answer is a take-or-skip recurrence: the best total up to position i is the larger of the best total up to i - 1 and the best total up to i - 2 plus the value at i. Keeping only the last two totals gives an O(n) time, O(1) space solution.
By Evin JohnPublished 8 min read
The task, restated
Picture a freelancer looking at a week of paid gigs laid out day by day. Each gig pays a known amount, and every gig is so tiring that taking one rules out the gig on the day right before and right after it. The freelancer wants the largest total pay. Stripped of the story: you get a list of non-negative integers, you choose any set of indexes with no two indexes adjacent, and you return the largest possible sum. The classic version frames the list as houses on a street with linked alarms, but the math is the same.
| Values | Best total | One choice that reaches it |
|---|---|---|
| [4, 1, 2, 7, 5, 3, 1] | 14 | 4 + 7 + 3 (indexes 0, 3, 5) |
| [2, 9, 3] | 9 | Just the 9; taking both ends gives only 5 |
| [6, 1, 1, 6, 1] | 12 | Both 6s, which are three apart |
| [3, 3, 3, 3] | 6 | Any two values that are not neighbors |
| [5] | 5 | The single value |
| [] | 0 | Nothing to take |
Two quick questions settle the edges. Can values be negative? In the usual statement they cannot, which is why skipping is always safe and an empty list returns 0. Do you need the total only, or also the chosen indexes? Most interviews start with the total and ask for the indexes as a follow-up.
Why interviewers pick it
This is often the first dynamic programming problem in a loop, because the state is tiny and the recurrence fits on one line. The interviewer is less interested in the final code than in how you get there: do you notice that a greedy rule fails, can you define what best(i) means in words, and can you shrink the memory once the table works. The [2, 9, 3] example kills the most common greedy idea, taking every other value starting from the first, and [6, 1, 1, 6, 1] kills the idea of always taking the larger of each neighboring pair.
- Return the chosen positions, not just the sum. Keep the full table and walk it backward, shown below.
- The row wraps into a circle. The first and last items become neighbors. See House Robber II.
- Values sit on a binary tree and a parent and child cannot both be taken. Each node returns a pair: best with the node taken and best with it skipped.
- Choosing a value deletes its neighbors by value, not by index. Count each value, then run the same recurrence over the sorted distinct values.
Brute force: try every allowed subset
At each index you either take the value and jump two steps ahead, or skip it and move one step ahead. A plain recursion explores both branches everywhere, so the number of calls grows like the Fibonacci numbers, roughly 1.6 to the power n. That is fine for ten values and hopeless for a thousand. Say it out loud as your starting point, then point at the repeated calls: the call for index 5 is made from index 3 (take) and from index 4 (skip), and each of those is reached several ways.
def best_pay_slow(pay, i=0):
if i >= len(pay):
return 0
take = pay[i] + best_pay_slow(pay, i + 2)
skip = best_pay_slow(pay, i + 1)
return max(take, skip)Turning the recursion into a recurrence
Define best(i) as the largest total you can collect from the first i + 1 values. For the value at i there are only two cases. If you skip it, the answer is whatever was best for the first i values, best(i - 1). If you take it, the value before it is off limits, so you add pay[i] to best(i - 2). The larger of those two is best(i). The base cases are best(-1) = 0 and best(-2) = 0, which is why the code below can start both rolling variables at zero.
| i | Value | Skip: best(i - 1) | Take: best(i - 2) + value | best(i) |
|---|---|---|---|---|
| 0 | 4 | 0 | 0 + 4 = 4 | 4 |
| 1 | 1 | 4 | 0 + 1 = 1 | 4 |
| 2 | 2 | 4 | 4 + 2 = 6 | 6 |
| 3 | 7 | 6 | 4 + 7 = 11 | 11 |
| 4 | 5 | 11 | 6 + 5 = 11 | 11 |
| 5 | 3 | 11 | 11 + 3 = 14 | 14 |
| 6 | 1 | 14 | 11 + 1 = 12 | 14 |
Each row reads only the two rows above it. That observation is the whole space optimization: instead of an array of n totals, keep two numbers, the best total two steps back and the best total one step back, and slide them forward.
Optimal approach: two rolling totals
def best_pay(pay):
two_back, one_back = 0, 0
for amount in pay:
two_back, one_back = one_back, max(one_back, two_back + amount)
return one_backfunction bestPay(pay) {
let twoBack = 0;
let oneBack = 0;
for (const amount of pay) {
const next = Math.max(oneBack, twoBack + amount);
twoBack = oneBack;
oneBack = next;
}
return oneBack;
}The Python tuple assignment evaluates the right side before writing either name, so the old one_back is used in both places. In JavaScript, updating twoBack before computing next would read the wrong value, which is why the temporary exists.
Follow-up: which positions were chosen
To return the indexes, keep the full table, then walk it from the end. At index i, if best(i) equals best(i - 1), the value at i was not needed, so step back one. Otherwise it was taken, so record i and step back two. The walk is linear, so the whole thing stays O(n) time, now with O(n) space.
def chosen_days(pay):
n = len(pay)
table = [0] * (n + 2) # table[k + 2] holds best(k); two zeros in front
for k, amount in enumerate(pay):
table[k + 2] = max(table[k + 1], table[k] + amount)
picked, k = [], n - 1
while k >= 0:
if table[k + 2] == table[k + 1]:
k -= 1
else:
picked.append(k)
k -= 2
return picked[::-1]For [4, 1, 2, 7, 5, 3, 1] this returns [0, 3, 5]. When several choices tie, it prefers skipping, so it returns one optimal answer rather than every optimal answer. Say that if the interviewer asks which one you return.
Time and space
| Version | Time | Extra space |
|---|---|---|
| Plain recursion | O(φ^n), about 1.6^n | O(n) call stack |
| Recursion with a memo | O(n) | O(n) memo plus O(n) stack |
| Bottom-up table | O(n) | O(n) |
| Two rolling totals | O(n) | O(1) |
Edge cases
- An empty list returns 0.
- One value returns that value; two values return the larger.
- All zeros returns 0, and the index rebuild returns an empty list because skipping wins every tie.
- Long lists: the rolling version has no recursion, so there is no stack depth problem. A memoized recursion in Python hits the default recursion limit near a thousand values.
- Values that would be negative in a variant: skipping still guarantees a total of at least 0, so the recurrence holds as long as an empty choice is allowed.
Mistakes to avoid
- Answering with the larger of the sum of even indexes and the sum of odd indexes. [6, 1, 1, 6, 1] gives 8 that way, and the real answer is 12.
- Writing best(i) = best(i - 2) + value[i] with no skip branch, which forces every other value to be taken.
- Updating the rolling variables in the wrong order in a language without tuple assignment.
- Starting the loop at index 2 and forgetting to handle lists of length 0 and 1 separately.
- Explaining the code before explaining what best(i) means. The definition is the part interviewers grade.
How to explain it out loud
Fictional example
- Candidate
- Taking every other value fails on 2, 9, 3, so I will not go greedy. Let best of i be the most I can collect from the first i plus one values.
- Candidate
- For the last of those values I either skip it and keep best of i minus one, or take it and add it to best of i minus two. The answer is the max of those.
- Candidate
- Each step looks back only two places, so I keep two numbers instead of an array. That is linear time and constant space, and if you want the indexes I can keep the table and walk it backward.
Related problems
House Robber II bends the row into a circle and solves it with two calls to the function on this page. Decode Ways uses the same look-back-two shape, but adds the two options together instead of taking a max. Coin Change keeps a full table because each amount may look back by any coin value, not just one or two steps.
Where Natively fits
When you drill dynamic programming on a Mac or Windows PC, Natively can read a problem like this one from a screenshot and suggest a recurrence and code to compare against your own attempt. It also transcribes your spoken explanation, so afterward you can check whether you defined best(i) before you started typing. The AI interview assistant page covers the setup.
Questions people ask
What is the recurrence for House Robber?
best(i) = max(best(i - 1), best(i - 2) + value[i]). You either skip the current value and keep the previous best, or take it and add it to the best total from two positions back.
Why does a greedy approach fail on House Robber?
Taking every other value, or always taking the bigger of two neighbors, ignores how one choice limits later ones. On [6, 1, 1, 6, 1] the alternating sums give 8 and 7, while taking both 6s gives 12.
What is the time and space complexity of House Robber?
The bottom-up solution runs in O(n) time. Because each step reads only the two previous totals, two variables replace the table and extra space drops to O(1).
How do you find which houses were robbed, not just the total?
Keep the full table and walk it from the end. If best(i) equals best(i - 1), skip index i; otherwise record i and jump back two. That rebuilds one optimal set in O(n).
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
