Start learning free

LESSON 522 OF 671 · DYNAMIC PROGRAMMING

House Robber in JavaScript: Dynamic Programming

Practice O(n) Read the full explanation

You get an array nums, the money in each house along a street. House i holds nums[i].

Return the most money you can rob.

Houses next to each other share an alarm. So you can never rob two neighbors.

Example 1:

Input: nums = [3, 10, 3, 1, 2]
Output: 12
Explanation: The best pick is house 1 (10) and house 4 (2).
That gives 10 + 2 = 12.
Robbing houses 0, 2 and 4 gives only 3 + 3 + 2 = 8.

Example 2:

Input: nums = [6, 1, 2, 7]
Output: 13
Explanation: Rob house 0 (6) and house 3 (7).
That gives 6 + 7 = 13.
Houses 1 and 2 are both skipped, and that is allowed.

Example 3:

Input: nums = [9]
Output: 9
Explanation: With one house, rob it.

Constraints:

  • 1 to 100 houses.
  • Each house holds from 0 to 400.

STEP 1 OF 6
    Ctrl + Enter to check

    JAVASCRIPT · DYNAMIC PROGRAMMING

    House Robber in JavaScript, explained

    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 - 1 must stay untouched, so the best total is the best for the houses before i - 1, plus nums[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

    1. Create prev with let, 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.
    2. Create curr the same way, also 0. It is the best total for the houses up to the one just before the current one.
    3. Loop over every house with i from 0 while i < nums.length.
    4. Compute best with Math.max: the larger of curr (skip the house) and prev + nums[i] (rob it). This one line is the whole algorithm.
    5. Move both totals one house to the right: prev = curr first, then curr = best. Doing it the other way round overwrites the value prev needs.
    6. 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 = best before prev = curr makes both variables equal best. 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
    
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free