House Robber
The problem
Section titled “The problem”Each house in a row holds some cash. If you rob two neighboring houses the alarm goes off, so you may never rob adjacent houses. Return the most money you can take.
nums = [2, 7, 9, 3, 1] -> 12 (rob 2 + 9 + 1)Key insight
Section titled “Key insight”Brute force tries every subset with no two adjacent, which is O(2^n). Greedy (“always
take the biggest”) fails: in [2, 3, 2] it takes the 3 and then can take nothing else,
but the best is 2 + 2.
At each house you make one choice: skip it, or rob it and give up the previous house.
So best[i] = max(best[i-1], best[i-2] + nums[i]), with best of nothing equal to 0.
Each value depends only on the previous two, so two rolling variables are enough.
Show solutionHide solution
def rob(nums: list[int]) -> int: two_back, one_back = 0, 0 # best loot up to i-2 and up to i-1 for money in nums: two_back, one_back = one_back, max(one_back, two_back + money) return one_backexport function rob(nums: number[]): number { let twoBack = 0, oneBack = 0; // best loot up to i-2 and up to i-1 for (const money of nums) { [twoBack, oneBack] = [oneBack, Math.max(oneBack, twoBack + money)]; } return oneBack;}class Solution { public int rob(int[] nums) { int twoBack = 0, oneBack = 0; // best loot up to i-2 and up to i-1 for (int money : nums) { int best = Math.max(oneBack, twoBack + money); twoBack = oneBack; oneBack = best; } return oneBack; }}Complexity
Section titled “Complexity”- Time: O(n) — one pass, constant work per house.
- Space: O(1) — two variables replace the full
bestarray.
Watch out for
Section titled “Watch out for”- Update both variables together. Overwriting
one_backbefore using it to settwo_backmixes up the two houses. Use a tuple swap or a temp variable. - Short inputs. One house must return its value, and an array of zeros must return 0. Starting both variables at 0 handles these without special cases.
- Don’t think “alternate houses”. The best plan can skip two in a row, such as
[100, 1, 1, 100].
Variations
Section titled “Variations”House Robber II (LeetCode 213)
Section titled “House Robber II (LeetCode 213)”The houses form a circle, so the first and last are neighbors. The trick: run the
linear solution twice, once on nums[0..n-2] and once on nums[1..n-1], and take the
larger result. Handle n = 1 separately.
Delete and Earn (LeetCode 740)
Section titled “Delete and Earn (LeetCode 740)”Taking value v earns v points but deletes every v-1 and v+1. The trick: sum
the points per value into an array indexed by value. Then it is exactly House Robber on
that array, because picking v forbids its neighbors.