Start learning free

LESSON 240 OF 314 · DYNAMIC PROGRAMMING

House Robber in TypeScript: O(n) 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

    TYPESCRIPT · DYNAMIC PROGRAMMING

    House Robber in TypeScript, explained

    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

    1. Create prev with let, 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.
    2. Create curr the same way, also 0. It is the best total for the houses up to the one just before the current house.
    3. Loop over every house with i from 0 while i < nums.length. Each house is decided once, using only totals from the houses before it.
    4. Compute best with Math.max: the larger of curr (skip the house) and prev + nums[i] (rob it).
    5. Move both totals one house to the right: prev = curr first, then curr = best. The other order would overwrite the value prev needs.
    6. 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 = 0 is inferred as number, so no annotation is needed. best is a number too, because Math.max returns one.
    • Math.max takes any number of arguments. Here it gets two. It is a plain function, not a method of arrays, so Math.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 gives undefined instead of an error, and prev + undefined would be NaN, 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 = best runs before prev = curr, both variables hold the same value and the "two houses back" total is lost.

    Testing

    • [1, 2, 3, 1] gives 4.
    • [2, 7, 9, 3, 1] gives 12.
    • [2, 1, 1, 2] gives 4.
    • [5] gives 5.
    • [3, 10] gives 10.
    • [0, 0, 0] gives 0.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free