Neighborhood TheftLoading saved progress…

Neighborhood Theft

You're a burglar casing a single street of houses lined up in a row, each holding some amount of loot. There's one catch: every house shares a security system with its immediate neighbours, so robbing two adjacent houses on the same night trips the alarm. Given the loot in each house, neighborhoodTheft(houses) returns the maximum total you can steal without ever picking two side-by-side houses. This is the classic "House Robber" dynamic-programming problem.

Signature

// houses: number[] — non-negative loot value for each house, left to right.
// returns: number   — the maximum total loot taken from a subset of houses
//                     in which no two chosen houses are adjacent.
function neighborhoodTheft(houses: number[]): number;

Examples

neighborhoodTheft([1, 2, 3, 1]); // → 4
// Rob house 0 (1) and house 2 (3): 1 + 3 = 4.
// You can't add house 1 or house 3 without sitting next to a robbed house.
neighborhoodTheft([2, 7, 9, 3, 1]); // → 12
// Rob house 0 (2), house 2 (9), and house 4 (1): 2 + 9 + 1 = 12.
// Taking the big 7 would block both 2 and 9, which together beat it.

Notes

  • Non-adjacent only. If you take house i, you cannot take house i - 1 or house i + 1. Houses two or more apart are fine.
  • Maximize the total, not the count of houses. Sometimes one fat house beats two thin ones; sometimes the reverse.
  • Empty input returns 0. No houses means no loot.
  • A single house returns its own value. With nothing adjacent, you always take it.
  • Values are non-negative (zero is allowed). You never lose money by taking a house, but a zero-value house is never worth blocking its neighbours for.
Loading editor…