Problem overview
The method rob(nums: number[]): number receives the money in each house along a street: house i holds nums[i]. Robbing two neighboring houses on the same night sets off an alarm, so the chosen houses can't be adjacent. The method returns the largest total that can be taken.
For nums = [2, 7, 9, 3, 1] the best choice is houses 0, 2 and 4, which gives 2 + 9 + 1 = 12. For [2, 1, 1, 2] the answer is 4, from houses 0 and 3. Robbing every other house would give only 3, so skipping two houses in a row can pay off.
Approach: decide house by house
Trying every allowed set of houses is exponential. Instead, walk along the street from left to right and keep the best total so far. For each house there are only two choices:
- Skip it. The best total stays what it was after the previous house.
- Rob it. Then the previous house must be untouched, so this house's money is added to the best total from two houses back.
The better of the two is the best total up to this house. Writing it as a formula, with best(i) for the best total using houses 0 to i:
best(i) = max(best(i - 1), best(i - 2) + nums[i])
Each value depends only on the two before it, so two running totals are enough, and no array is needed. Reusing the answers for shorter streets instead of recomputing them is what makes this dynamic programming.
Step by step
- Create
prevwithlet, starting at 0. It is the best total for the houses up to two before the current one. Before the first house nothing has been robbed, so both totals start at 0. - Create
currthe same way, also 0. It is the best total for the houses up to the one just before the current house. - Loop over every house with
ifrom 0 whilei < nums.length. Each house is decided once, using only totals from the houses before it. - Compute
bestwithMath.max: the larger ofcurr(skip the house) andprev + nums[i](rob it). - Move both totals one house to the right:
prev = currfirst, thencurr = best. The other order would overwrite the valueprevneeds. - Return
curr. After the last house it is the best total for the whole street.
Tracing nums = [2, 7, 9, 3, 1]:
start prev=0 curr=0
i=0 house=2 best=2 prev=0 curr=2
i=1 house=7 best=7 prev=2 curr=7
i=2 house=9 best=11 prev=7 curr=11
i=3 house=3 best=11 prev=11 curr=11
i=4 house=1 best=12 prev=11 curr=12
At i = 2 robbing the 9 on top of the 2 from house 0 (11) beats keeping the 7 from house 1. At i = 3 the 3 would only add up to 7 + 3 = 10, so the total stays at 11. The function returns 12.
The solution in TypeScript
class Solution {
rob(nums: number[]): number {
let prev = 0;
let curr = 0;
for (let i = 0; i < nums.length; i++) {
const best = Math.max(curr, prev + nums[i]);
prev = curr;
curr = best;
}
return curr;
}
}
The TypeScript details worth knowing:
- Inferred types.
let prev = 0is inferred asnumber, so no annotation is needed.bestis anumbertoo, becauseMath.maxreturns one. Math.maxtakes any number of arguments. Here it gets two. It is a plain function, not a method of arrays, soMath.max(nums)would not find the largest element.- Numbers are doubles. The constraints keep the totals tiny (at most 100 houses of at most 400), so exactness is never an issue.
- Reading out of range. The loop only reads
nums[i]for valid indices. In TypeScript an out-of-range read givesundefinedinstead of an error, andprev + undefinedwould beNaN, which is a silent bug in any off-by-one version of this loop.
Complexity
Time: O(n), where n is the number of houses. The loop visits each house once and does constant work. Space: O(1), because only prev, curr, best and i exist. Keeping a full array of best totals would work as well and cost O(n) space.
Edge cases and common mistakes
- One house.
[5]gives 5:best = max(0, 0 + 5). - Two houses.
[3, 10]gives 10. The two houses are neighbors, so only the larger can be robbed. - Empty input. The constraints promise at least one house, but an empty array simply returns 0, because the loop never runs.
- All zeros.
[0, 0, 0]gives 0. - Greedy alternation. Taking houses 0, 2, 4 and so on, or only the even or odd positions, fails on
[2, 1, 1, 2]: it gives 3 while the answer is 4. The recurrence compares both choices at every house instead of following a fixed pattern. - Always taking the biggest house first. This is another greedy shortcut that can fail, because a big house can block two neighbors worth more together. The recurrence never commits early.
- Updating in the wrong order. If
curr = bestruns beforeprev = curr, both variables hold the same value and the "two houses back" total is lost.
Testing
[1, 2, 3, 1]gives4.[2, 7, 9, 3, 1]gives12.[2, 1, 1, 2]gives4.[5]gives5.[3, 10]gives10.[0, 0, 0]gives0.
