Problem overview
The method rob receives nums, the money in each house along a street. You may rob any set of houses as long as no two of them are neighbors, and the method returns the largest total you can take.
With nums = [2, 7, 9, 3, 1] the best choice is houses 0, 2 and 4, giving 2 + 9 + 1 = 12. With [2, 1, 1, 2] it is houses 0 and 3, giving 4. Robbing every other house starting from the first would give only 2 + 1 = 3 there, so a fixed pattern doesn't work and the code has to decide house by house.
Approach: rob it or skip it
Look at the houses from left to right. For house i there are two choices:
- Skip it. The best total is whatever was best for the houses before it.
- Rob it. House
i - 1must stay untouched, so the best total is the best for the houses beforei - 1, plusnums[i].
The larger of the two is the best total up to house i. This uses only the two previous results, so two running totals are enough: no array and no recursion. That is dynamic programming in its smallest form, where each answer reuses answers to shorter streets.
Trying every valid set of houses would take exponential time, since each house is either in or out. Comparing running totals, as above, does the same job in one pass.
Step by step
- Create
prevwithlet, set to 0. It is the best total for the houses up to two before the current one. Before the first house nothing has been robbed. - Create
currthe same way, also 0. It is the best total for the houses up to the one just before the current one. - Loop over every house with
ifrom 0 whilei < nums.length. - Compute
bestwithMath.max: the larger ofcurr(skip the house) andprev + nums[i](rob it). This one line is the whole algorithm. - Move both totals one house to the right:
prev = currfirst, thencurr = best. Doing it the other way round overwrites the valueprevneeds. - Return
curr. After the last house it is the best total for the whole street.
The solution in JavaScript
class Solution {
rob(nums) {
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;
}
}
On the JavaScript side, Math.max takes any number of arguments and returns the largest one. The counters are declared with let because they change, and best is a const that exists only for one round of the loop.
Tracing [2, 7, 9, 3, 1]
The totals after each house, starting with prev = 0 and curr = 0:
i=0 x=2 best=2 prev=0 curr=2
i=1 x=7 best=7 prev=2 curr=7
i=2 x=9 best=11 prev=7 curr=11
i=3 x=3 best=11 prev=11 curr=11
i=4 x=1 best=12 prev=11 curr=12
At house 3 the choice is between skipping it (11) and robbing it for 7 + 3 = 10, so the total stays 11. At house 4, robbing it adds 1 to the 11 from two houses back, which gives 12.
Complexity
The loop visits each house once and does constant work, so the time is O(n), where n is nums.length. Only prev, curr and best are stored, so the space is O(1).
Edge cases and common mistakes
- One house.
rob([5])returns 5:Math.max(0, 0 + 5). Starting both totals at 0 handles this without a special case. - Houses holding 0.
rob([0, 0])returns 0. The constraints allow 0, and the code needs no special handling for it. - Wrong update order. Writing
curr = bestbeforeprev = currmakes both variables equalbest. On[2, 7, 9, 3, 1]the method then returns 22, which is more than the possible 12, because adjacent houses get counted together. - Taking every other house. It fails on
[2, 1, 1, 2], where the answer is 4 but alternating gives 3.
Testing
Results from the reference solution:
[1, 2, 3, 1] -> 4
[2, 7, 9, 3, 1] -> 12
[2, 1, 1, 2] -> 4
[5] -> 5
[0, 0] -> 0
[3, 10, 3, 1, 2] -> 12
