Start learning free

LESSON 240 OF 314 · DYNAMIC PROGRAMMING

House Robber in Scala: Dynamic Programming with Two Running Totals

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

    SCALA · DYNAMIC PROGRAMMING

    House Robber in Scala, explained

    Problem overview

    The method rob receives an array nums where nums(i) is the money in house i. Robbing two neighboring houses on the same night triggers an alarm, so no two chosen houses may be next to each other. The method returns the largest total you can take.

    For [1, 2, 3, 1] the best choice is houses 0 and 2, which gives 1 + 3 = 4. For [2, 7, 9, 3, 1] it is houses 0, 2 and 4: 2 + 9 + 1 = 12. The constraints give between 1 and 100 houses with 0 to 400 in each.

    Approach: decide house by house

    Trying every allowed set of houses works only for tiny streets, since the number of sets doubles with each house. Instead, walk from left to right and keep the best total for the houses seen so far.

    When you reach house i, you have two options:

    • Skip it. The best total is then the best for the houses before it, which is curr.
    • Rob it. House i - 1 must stay untouched, so the money from house i adds to the best total for the houses up to i - 2, which is prev + nums(i).

    The larger of the two is the best total up to house i. That choice is the whole algorithm. Each answer uses only the previous two, so two variables replace a whole table of answers.

    Taking every other house is not always optimal. For [2, 1, 1, 2] the even-indexed houses give 2 + 1 = 3 and the odd-indexed ones give 1 + 2 = 3, but robbing houses 0 and 3 gives 4.

    Step by step

    1. Create prev with var, starting at 0. It is the best total for the houses up to two before the current one. Before any house, nothing has been robbed.
    2. Create curr the same way, starting at 0. It is the best total for the houses up to the one just before the current one.
    3. Loop i over 0 until nums.length. Every house is decided once.
    4. Compute best with math.max. It is the larger of curr (skip) and prev + nums(i) (rob), stored in a val.
    5. Move both totals one house to the right. Set prev to curr, then curr to best. Doing it in the other order would overwrite the value prev needs.
    6. End with curr. After the last house it is the best total for the whole street.

    Here is the loop on [2, 1, 1, 2]:

    i=0 best=2 prev=0 curr=2
    i=1 best=2 prev=2 curr=2
    i=2 best=3 prev=2 curr=3
    i=3 best=4 prev=3 curr=4

    At i = 1 skipping wins (2 against 0 + 1). At i = 3 robbing wins: prev + nums(3) is 2 + 2 = 4, while skipping would keep 3.

    The solution in Scala

    class Solution {
    
        def rob(nums: Array[Int]): Int = {
            var prev = 0
            var curr = 0
            for (i <- 0 until nums.length) {
                val best = math.max(curr, prev + nums(i))
                prev = curr
                curr = best
            }
            curr
        }
    }
    

    The Scala details worth a closer look:

    • Arrays use parentheses. Scala reads element i as nums(i), not nums[i]. Square brackets in Array[Int] are for types.
    • until excludes its end. 0 until nums.length visits indices 0 to length - 1, exactly the valid ones. Writing 0 to nums.length would read one element past the end and throw an ArrayIndexOutOfBoundsException.
    • math.max. It is the standard way to take the larger of two numbers, here two Int values.
    • The last expression is the result. The final curr is the return value, with no return keyword.

    Complexity

    Time: O(n), where n is the number of houses. Each house is handled once with a constant amount of work.

    Space: O(1). The method keeps prev, curr, best and the loop index, and never copies the array.

    Edge cases and common mistakes

    • One house. For [5], best is max(0, 0 + 5) = 5. The starting zeros make this case need no special code.
    • Two houses. For [1, 2] the method returns 2: you can take only one of the neighbors, and the larger is better.
    • Zeros. [0, 0] returns 0. Since money is never negative, robbing never lowers a total.
    • Greedy by alternating. Always taking houses 0, 2, 4 and so on fails on [2, 1, 1, 2], as shown above. Another case is [100, 1, 1, 100], which returns 200 by taking the two ends.
    • Updating in the wrong order. If curr changes before prev is set, prev and curr end up equal and the next round adds the wrong value.
    • Empty input. The constraints promise at least one house, but an empty array would return 0, because the loop does not run.

    Testing

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