Start learning free

LESSON 240 OF 314 · DYNAMIC PROGRAMMING

House Robber in Rust: 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

    RUST · DYNAMIC PROGRAMMING

    House Robber in Rust, explained

    Problem overview

    The function rob receives a vector nums where nums[i] is the money in house i. Two neighboring houses can't both be robbed, and the function returns the largest total you can take.

    For [1, 2, 3, 1] the answer is 4: houses 0 and 2 give 1 + 3. For [2, 7, 9, 3, 1] it is 12 (houses 0, 2 and 4: 2 + 9 + 1). For [2, 1, 1, 2] it is 4: houses 0 and 3. Taking every other house is not always best, since that choice gives only 3 here.

    Approach: decide house by house

    Trying every valid set of houses works, but the number of sets grows exponentially. A simpler view: walk along the street and, at each house, ask what the best total is for the houses up to and including this one. There are only two choices:

    • Skip the house. The best total is the best for the houses before it.
    • Rob the house. The previous house must stay untouched, so the money adds to the best total for the houses up to two before.

    The larger of the two is the answer for this house. Each answer is built from two earlier answers, which is dynamic programming. Because only the last two answers are ever needed, two variables replace a table.

    Take [2, 7, 9, 3, 1]. After each house, prev and curr hold:

    house 2: prev=0  curr=2
    house 7: prev=2  curr=7
    house 9: prev=7  curr=11
    house 3: prev=11 curr=11
    house 1: prev=11 curr=12

    The final curr, 12, is the answer.

    Step by step

    1. Create prev with let mut, set to 0. At the start of each round 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, also 0. It is the best total for the houses up to the one just before the current one.
    3. Loop over the houses with for i in 0..nums.len(). Each house is decided once, using only totals for the houses before it.
    4. Compute best as curr.max(prev + nums[i]): skip the house and keep curr, or rob it and add its money to prev. This one line is the whole algorithm.
    5. Move both totals one house to the right: prev becomes curr, then curr becomes best. If curr were assigned first, prev would pick up the new value and the old one would be lost.
    6. Return curr with no semicolon. After the last house it is the best total for the whole street.

    The solution in Rust

    impl Solution {
        fn rob(nums: Vec<i32>) -> i32 {
            let mut prev = 0;
            let mut curr = 0;
            for i in 0..nums.len() {
                let best = curr.max(prev + nums[i]);
                prev = curr;
                curr = best;
            }
            curr
        }
    }
    

    The Rust details worth a closer look:

    • max is a method. a.max(b) returns the larger of two values of the same type, here i32. The type of curr is inferred from nums[i], so curr and prev are i32 without annotations.
    • 0..nums.len() is a range of usize values, which is what indexing a vector requires. The upper end is excluded, so i never reaches nums.len().
    • nums is owned. The function takes the vector by value, and indexing with nums[i] copies an i32 out of it. Indexing out of bounds would panic, but the range makes that impossible here.
    • mut only where needed. prev and curr change in the loop, while best is assigned once per round with a plain let.
    • The last expression. curr without a semicolon is the function's return value.

    Complexity

    Time: O(n), where n is the number of houses: one pass, with constant work per house.

    Space: O(1). Only prev, curr and best are kept. The input vector is not counted.

    Edge cases and common mistakes

    • One house. [5] returns 5: curr.max(prev + 5) is 0.max(5).
    • An empty vector. The constraints rule it out, but the loop would simply not run and the function would return 0.
    • Two houses. [3, 10] returns 10: you rob one of them, the richer one.
    • Alternating houses. Robbing every other house fails on [2, 1, 1, 2], where the best answer skips two houses in a row. The recurrence handles it, as curr goes 2, 2, 3, 4.
    • Adding to curr instead of prev. curr + nums[i] would rob a house next to the one just considered, which breaks the rule.
    • Zeros. [0, 0, 0] returns 0. Money is never negative, so skipping a house never costs anything.

    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.
    • [4, 1, 1, 4, 1, 1, 4] gives 12.
    • [0, 0, 0] gives 0.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free