House robber (recursion)
Medium TimeO(2ⁿ) naive; O(n) memoised SpaceO(n) stack
A row of houses each hold some money, but robbing two next to each other sets off the alarm. Return the most that can be taken. The row does not wrap around, so the first and last houses are not adjacent, and taking nothing is allowed, so the answer is never negative.
Examples
Example 1
- Input
- nums = [2, 7, 9, 3, 1]i = 0
- Output
122 + 9 + 1= 12; the richer-looking7 + 3comes to only 10.
Example 2
- Input
- nums = [5, 1, 1, 5]i = 0
- Output
105 + 5at the two ends, with both1s between them skipped.
The Code
function rob(nums, i) {
if (i >= nums.length) return 0;
const robThis = nums[i] + rob(nums, i + 2);
const skip = rob(nums, i + 1);
return Math.max(robThis, skip);
}
rob([2, 7, 9, 3, 1], 0);Done
The first 17 calls, of 25. This one does not fit on a page.
More like this
All dynamic programming examples (20) →- Climbing stairs Count the ways to the top — Fibonacci in disguise.
- Coin change Try every coin and keep the cheapest way to make the amount.
- Max subarray One pass, two running totals — Kadane’s algorithm.
- LCS Match a character or drop one from either string.
- Edit distance Insert, delete, or replace — take the cheapest at each mismatch.
- 0/1 Knapsack For each item, take it or leave it — keep the more valuable branch.