Start learning free

LESSON 240 OF 314 · DYNAMIC PROGRAMMING

House Robber in C++: Dynamic Programming with Two Running Totals

Practice O(n) Read the full explanation

You get a vector 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

    C++ · DYNAMIC PROGRAMMING

    House Robber in C++, explained

    Problem overview

    The method rob receives a vector nums where nums[i] is the money in house i. You may rob any set of houses as long as no two neighbours are both robbed. It returns the largest total you can collect.

    For nums = [2, 7, 9, 3, 1] the answer is 12: robbing houses 0, 2 and 4 gives 2 + 9 + 1. The third example, [2, 1, 1, 2], shows that the best plan can skip two houses in a row: robbing the two ends gives 4, while robbing every other house gives only 3.

    Approach: rob it or skip it

    Go through the houses from left to right and decide each one. For house i there are two choices:

    • Skip it. The best total is then the best total for the houses before it.
    • Rob it. Then house i - 1 must stay untouched, so the money in house i is added to the best total for the houses before house i - 1.

    The better of the two is the best total up to house i. Each decision needs only two earlier answers, so two running totals are all the program keeps. This is dynamic programming: every answer is built from answers to smaller versions of the problem.

    Why two totals are enough: whether house i is robbed only changes what is allowed for house i - 1. Nothing earlier than that can clash with it, so the best totals for the two most recent prefixes carry all the information the next decision needs.

    Step by step

    1. Create prev as 0. At the start of each round it is the best total for the houses up to two before the current one.
    2. Create curr as 0. It is the best total for the houses up to the one just before the current one. Before the first house nothing has been robbed, so both are 0.
    3. Loop over every house with an index i from 0 while i < nums.size(). Each house is decided exactly once.
    4. Compute best as max(curr, prev + nums[i]): skip the house and keep curr, or rob it and add its money to prev.
    5. Slide both totals one house to the right. prev takes curr, then curr takes best. Doing it the other way round would overwrite the value prev needs.
    6. Return curr. After the last house it is the best total for the whole street.

    The solution in C++

    class Solution {
    public:
        int rob(vector<int>& nums) {
            int prev = 0;
            int curr = 0;
            for (int i = 0; i < nums.size(); i++) {
                int best = max(curr, prev + nums[i]);
                prev = curr;
                curr = best;
            }
            return curr;
        }
    };
    

    For nums = [2, 7, 9, 3, 1] the variables change like this, with prev and curr shown after the round:

    inums[i]bestprevcurr
    02202
    17727
    2911711
    33111111
    41121112

    At house 3 the money (3) added to prev (7) gives 10, which is less than curr (11), so the house is skipped and the total stays at 11. At house 4, robbing wins: 11 + 1 = 12.

    The example [2, 1, 1, 2] shows why comparing both options matters. After each round curr is 2, 2, 3 and 4. At house 1, robbing would give 0 + 1 = 1, less than the 2 already kept, so the house is skipped. At house 2, robbing gives 2 + 1 = 3 and wins. At house 3, prev is 2, so robbing gives 2 + 2 = 4, which beats the 3 from skipping. The final plan robs houses 0 and 3 and leaves two houses in a row alone.

    The C++ details:

    • vector<int>& nums takes the vector by reference, so no copy is made. The function only reads it.
    • max comes from the standard library and needs both arguments to have the same type, which they do here (int and int).
    • nums.size() is unsigned. Comparing it with the signed i is fine here because i never goes below zero, but the compiler may warn about it. With an empty vector, nums.size() - 1 would wrap around to a huge number, which is why the loop uses i < nums.size() and not i <= nums.size() - 1.

    Complexity

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

    Space: O(1): prev, curr, best and the loop index, whatever the street's length.

    Edge cases and common mistakes

    • One house. [5] returns 5: best = max(0, 0 + 5).
    • All zeros. [0, 0] returns 0. Zero is allowed by the constraints, and nothing special is needed.
    • Taking every other house. It looks natural but fails: for [2, 1, 1, 2] it gives 3, while the code returns 4. For [10, 1, 1, 10] the answer is 20, from the two ends.
    • Greedy by the largest house. Robbing the biggest house first can block two good neighbours. The two-choice rule compares both options at every house instead.
    • Starting the totals at something other than 0. With prev and curr both 0, the first house follows the same rule as every other house. A special start value would need a special case for it.

    Testing

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