House robber
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
House robber picks values from a row so no two chosen items are neighbours, aiming for the biggest total. At each item you compare "take it and skip the previous" against "skip it and keep what I had". It is the model for any choice where picking one thing blocks the next.
Practical use cases
- Web app: Clinic booking with no back-to-back slots. A clinic's booking tool lets a doctor accept appointments with a rest gap, so no two chosen slots are adjacent. Each slot has a fee, and the doctor wants the highest daily income. For every slot the code compares taking it with the best total two slots earlier against skipping it, and the answer comes out in one pass.
- Web app: Ad placement on a page. A news page has a column of ad positions with different revenues, but advertisers do not want two ads side by side. The page picks the set of non-adjacent positions with the best total. A single loop finds it without trying every combination. Revenue per position changes daily, so the page reruns the loop each morning, and the ad team always sees the best non-adjacent set in a fraction of a second.
- System: Crop planning and playlist picking. A farm plan might not use two neighbouring fields in the same season. A playlist builder might avoid two similar songs in a row. Both are neighbour-blocking choices. In each of these, picking something blocks its neighbour, so the best answer comes from comparing take-it against skip-it at every position instead of chasing the biggest value.
The story: The Sweet Lane on Diwali Night
On Diwali night, the kids of Mira's mohalla go trick-or-treating, Indian style: knocking on doors for laddoos and barfi. Each house in the lane gives a different number of sweets. But the mohalla has a funny rule: if you visit two houses next to each other, the aunties compare notes and nobody gives you anything more. So no two neighbours!
Kabir's plan was simple: always grab the biggest house first. But in a tiny lane with 5, 9 and 5 sweets, his plan takes the 9 and gets blocked on both sides, ending with 9, while the two outer houses together give 10. "Greed is not always right," said Mira. "For each house, let us ask the only question that matters: take it, or skip it?"
If you take house i, you cannot have house i-1, so your total is this house's sweets plus the best total up to house i-2. If you skip it, your total is simply the best up to house i-1. Pick the larger. Fill a table house by house, and the last box is the answer.
This puzzle is famous as House Robber (in the textbook version the person is a robber, but our kids stick to sweets!). It is the classic example of a DP choice: take or skip.
How to spot this problem, and where you need it
You must choose items from a line for the best total, but choosing an item forbids its neighbours, so greedy picking of the biggest items often goes wrong.
Signs you need it
- The problem says "no two adjacent", "cannot pick consecutive", or "must leave a gap".
- Picking the largest value first sometimes blocks two nearly as large neighbours and gives a worse total.
- Each decision is simply take or skip, and taking affects only the item right next to it.
Where to use it in a project
- Scheduling slots or appointments that need a gap between them.
- Selecting ad, banner or promotion positions where neighbours must not both be used.
The solution
Keep two numbers: the best total up to the previous item, and the best total up to the item before that. For each new item, the best total is the larger of (best up to previous item) and (this item's value plus best up to two items back). Then slide the two numbers forward. After the last item, the stored best total is your answer, found in a single loop.
Payoff: Before: trying every possible selection, over a million for 20 slots. After: one pass with 20 comparisons.
Explain it like I am 8
You are choosing sweets from a row of jars, but you may not take from two jars side by side. For every jar you ask: "Is it better to grab this jar and give up its neighbour, or to skip this jar and keep what I already have?" You pick whichever gives more.
How it works, step by step
- State:
dp[i]= the most sweets you can collect using houses0..i. - Base cases:
dp[0] = a[0], anddp[1] = max(a[0], a[1])(neighbours, so only one). - Transition:
dp[i] = max(dp[i-1], dp[i-2] + a[i]): skip it, or take it and jump over its neighbour. - Fill left to right. The last box is the best total.
- To find which houses: walk back from the end. If
dp[i]equalsdp[i-1]the house was skipped; otherwise it was taken, then jump toi-2.
The code in four languages
PHP
<?php
// Take-or-skip with a "no neighbours" rule. Returns the best total and the chosen houses.
function bestLane(array $a): array {
$n = count($a);
if ($n === 0) return [0, []];
$dp = [$a[0]]; // dp[i] = best total using houses 0..i
if ($n > 1) $dp[1] = max($a[0], $a[1]);
for ($i = 2; $i < $n; $i++) {
$dp[$i] = max($dp[$i - 1], // skip house i
$dp[$i - 2] + $a[$i]); // take house i, jump over its neighbour
}
// Walk back to find which houses were taken.
$chosen = [];
$i = $n - 1;
while ($i >= 0) {
if ($i === 0 || $dp[$i] !== $dp[$i - 1]) { $chosen[] = $i; $i -= 2; }
else $i -= 1;
}
return [$dp[$n - 1], array_reverse($chosen)];
}
[$best, $houses] = bestLane([6, 7, 1, 30, 8, 2, 4]);
echo $best, " from houses ", implode(",", $houses), "\n"; // 41 from houses 1,3,6JavaScript
// Take-or-skip with a "no neighbours" rule. Returns the best total and the chosen houses.
function bestLane(a) {
const n = a.length;
if (n === 0) return [0, []];
const dp = [a[0]]; // dp[i] = best total using houses 0..i
if (n > 1) dp[1] = Math.max(a[0], a[1]);
for (let i = 2; i < n; i++) {
dp[i] = Math.max(dp[i - 1], // skip house i
dp[i - 2] + a[i]); // take house i, jump over its neighbour
}
// Walk back to find which houses were taken.
const chosen = [];
let i = n - 1;
while (i >= 0) {
if (i === 0 || dp[i] !== dp[i - 1]) { chosen.push(i); i -= 2; }
else i -= 1;
}
return [dp[n - 1], chosen.reverse()];
}
const [best, houses] = bestLane([6, 7, 1, 30, 8, 2, 4]);
console.log(best + " from houses " + houses.join(",")); // 41 from houses 1,3,6Java
import java.util.*;
public class Main {
// Take-or-skip with a "no neighbours" rule. Returns the best total and the chosen houses.
record Result(int best, List<Integer> houses) {}
static Result bestLane(int[] a) {
int n = a.length;
if (n == 0) return new Result(0, List.of());
int[] dp = new int[n]; // dp[i] = best total using houses 0..i
dp[0] = a[0];
if (n > 1) dp[1] = Math.max(a[0], a[1]);
for (int i = 2; i < n; i++) {
dp[i] = Math.max(dp[i - 1], // skip house i
dp[i - 2] + a[i]); // take house i, jump over its neighbour
}
// Walk back to find which houses were taken.
List<Integer> chosen = new ArrayList<>();
int i = n - 1;
while (i >= 0) {
if (i == 0 || dp[i] != dp[i - 1]) { chosen.add(i); i -= 2; }
else i -= 1;
}
Collections.reverse(chosen);
return new Result(dp[n - 1], chosen);
}
public static void main(String[] args) {
Result r = bestLane(new int[]{6, 7, 1, 30, 8, 2, 4});
StringJoiner houses = new StringJoiner(",");
for (int h : r.houses()) houses.add(String.valueOf(h));
System.out.println(r.best() + " from houses " + houses); // 41 from houses 1,3,6
}
}Go
package main
import (
"fmt"
"slices"
)
// Take-or-skip with a "no neighbours" rule. Returns the best total and the chosen houses.
func bestLane(a []int) (int, []int) {
n := len(a)
if n == 0 {
return 0, nil
}
dp := make([]int, n) // dp[i] = best total using houses 0..i
dp[0] = a[0]
if n > 1 {
dp[1] = max(a[0], a[1])
}
for i := 2; i < n; i++ {
dp[i] = max(dp[i-1], // skip house i
dp[i-2]+a[i]) // take house i, jump over its neighbour
}
// Walk back to find which houses were taken.
var chosen []int
i := n - 1
for i >= 0 {
if i == 0 || dp[i] != dp[i-1] {
chosen = append(chosen, i)
i -= 2
} else {
i--
}
}
slices.Reverse(chosen)
return dp[n-1], chosen
}
func main() {
best, houses := bestLane([]int{6, 7, 1, 30, 8, 2, 4})
fmt.Println(best, "from houses", houses) // 41 from houses [1 3 6]
}Time: O(n) · Extra space: O(n). One pass over the houses. If you only need the total (not which houses), two variables are enough: O(1) space.
Watch out for
- Being greedy: grabbing the biggest house first can block a better pair. Always compare take versus skip.
- Wrong second base case:
dp[1]must be the max of the first two houses, not their sum. - Forgetting the empty-lane and single-house cases, which crash on
a[1].
Quick check
- If you take house i, which earlier best do you build on?
- The best up to house i-1
- The best up to house i-2
- The best up to house 0
- Lane of sweets [2, 7, 9, 3, 1]. What is the best total?
- 12
- 10
- 9
- Why does greedy (always take the biggest) fail?
- It is too slow
- Taking a big house can block two neighbours that together are worth more
- It sorts the lane