House Robber

Pick houses along a street, never two side by side, to collect the most money.

A street has a row of houses, and nums[i] is the money kept in house i. Houses that stand side by side share an alarm, so robbing two neighbours sets it off. Return the most money you can rob without setting off any alarm.

Example 1
Input: nums = [1, 2, 3, 1]
Output: 4
Explanation: rob houses 0 and 2: 1 + 3.
Example 2
Input: nums = [2, 7, 9, 3, 1]
Output: 12
Explanation: rob houses 0, 2 and 4: 2 + 9 + 1.
Example 3
Input: nums = [2, 1, 1, 2]
Output: 4
Explanation: rob houses 0 and 3: 2 + 2.
Solution

The Idea

Picture yourself walking down the street of Example 2 with a bag. The five houses hold 2, 7, 9, 3 and 1, in that order. At each door you decide: take the money, or walk past. The one rule is that two houses next to each other can never both be taken.

Simple plans come to mind first. Taking every other house gives 2 + 9 + 1 = 12 here, which happens to be the answer. Example 3, [2, 1, 1, 2], breaks that plan: houses 0 and 2 give 3, houses 1 and 3 give 3, yet houses 0 and 3 give 4. Walking past two houses in a row is allowed, and sometimes it pays.

Taking the biggest amount first fails too. On the street [2, 3, 2] it takes the 3, and then neither 2 may be touched, so it ends with 3 instead of 2 + 2 = 4. So how do you decide at a door, when taking the money there can block something better further on?

Turn the question around. Stand at house 2, which holds 9, and ask for the most money from houses 0 to 2. There are two cases. If you walk past house 2, the best haul is the most money from houses 0 and 1. If you take it, house 1 must have been passed, so the best haul is the most money from house 0 alone, plus 9.

Both cases only need answers for shorter stretches of the street. So write those answers in a row under the houses, one entry per house: the entry under house i is the most money from houses 0 to i. Look at the picture below.

The street 2, 7, 9, 3, 1 with the most money from houses 0 to each house below it: 2, 7, 11, 11, 12. At house 2, skip it gives 7, rob it gives 2 + 9 = 11, and the larger, 11, is kept.

The top row, labelled "money in the house", is the street. In the bottom row, labelled "most money from houses 0 to here", the first two entries are easy. House 0 alone gives 2, and from houses 0 and 1 the better single house gives 7.

Now look at house 2. The teal arrow, "skip it: 7", copies the entry for house 1. The orange curve, "rob it: 2 + 9 = 11", takes the entry for house 0 and adds the 9. The larger of the two, 11, goes into the entry for house 2.

House 3 works the same way: skipping it gives 11, robbing it gives 7 + 3 = 10, so its entry is 11. House 4 gives the larger of 11 and 11 + 1 = 12, and that 12 is the answer to Example 2. Each entry needs only the two entries before it, so one pass from left to right fills the row.

Building the answer for houses 0 to i from answers already written down for shorter stretches of the street, instead of trying every set of houses, is called dynamic programming.

Solution Approach

Turning that idea into code starts with why trying every set of houses is slow. Then three things need settling: what each entry holds, where the row starts, and how much of the row to keep.

Trying every set of houses

Why not try every set of houses with no two neighbours and keep the best sum? Five houses allow 13 such sets, counting the empty one, so checking them all is quick. But the count grows with every house: 17,711 sets for 20 houses, and 267,914,296 for 40.

A method that calls itself for shorter stretches of the street is no faster. It finds the most money from houses 0 to i by calling itself for houses 0 to i - 1 and for houses 0 to i - 2. Those calls ask the same questions again and again: for 30 houses the method makes 4,356,617 calls. The row in the picture answers each question once.

What each entry holds

How is one entry worked out? Call the entry for house i best(i): the most money from houses 0 to i. It is the larger of the two cases from the picture:

  • skip house i: best(i - 1);
  • rob house i: best(i - 2) + nums[i], because house i - 1 must then be skipped.

In one line, best(i) = max(best(i - 1), best(i - 2) + nums[i]).

Where the row starts

What do best(0) and best(1) use, when there is no house -1 or -2? Count the stretch before house 0 as worth 0: no houses, no money. Then best(0) is the larger of 0 and 0 + 2, which is 2, and best(1) is the larger of 2 and 0 + 7, which is 7. Those are the first two entries in the picture.

With both starting values at 0, an empty street gives 0, and a street with one house gives that house's money.

Keeping two numbers instead of a row

Does the whole row have to be kept? In the picture, the entry for house 2 used only the entries for houses 0 and 1. So two numbers are enough: the newest entry and the one before it. Keeping only those is an optional saving in memory; a full row of entries gives the same answers.

Java Solution

The method rob works in these steps:

  1. First, set up two running totals, both 0. best is the most money from the houses before the current one, and bestTwoBack the most money from the houses before the previous one. At the start they stand for the empty stretch before house 0.
  2. Walk along the street with a for loop that takes each house's money as money.
  3. Inside the loop, compute robHere = bestTwoBack + money, the total if this house is robbed.
  4. Move bestTwoBack forward to the old best, then set best to the larger of best (skip this house) and robHere. Now best covers the houses up to this one.
  5. When the loop has passed every house, best holds the most money from the whole street, and the method returns it.

The main method runs the three examples, the street [2, 3, 2] where taking the biggest amount first goes wrong, a street of one house, and an empty street.

Java
import java.util.Arrays;

public class HouseRobber {

    public static int rob(int[] nums) {
        int bestTwoBack = 0;   // most money from the houses before the previous one
        int best = 0;          // most money from the houses before this one
        for (int money : nums) {
            int robHere = bestTwoBack + money;    // rob this house: the previous one is skipped
            bestTwoBack = best;
            best = Math.max(best, robHere);       // or skip it and keep the old best
        }
        return best;
    }

    public static void main(String[] args) {
        int[][] streets = {
            {1, 2, 3, 1},
            {2, 7, 9, 3, 1},
            {2, 1, 1, 2},
            {2, 3, 2},
            {5},
            {}
        };
        for (int[] nums : streets) {
            System.out.println(Arrays.toString(nums) + " -> " + rob(nums));
        }
    }
}

Running it prints:

Output
[1, 2, 3, 1] -> 4
[2, 7, 9, 3, 1] -> 12
[2, 1, 1, 2] -> 4
[2, 3, 2] -> 4
[5] -> 5
[] -> 0

Look at the second line: [2, 7, 9, 3, 1] gives 12, the last entry of the bottom row in the picture. [2, 1, 1, 2] gives 4 from houses 0 and 3, the pick that every-other-house plans miss. [2, 3, 2] also gives 4, from the two 2s on either side of the 3.

The last two lines are the smallest streets. [5] returns its own 5. The empty street [] returns 0, because the loop never runs and best keeps its starting 0.

The order of the lines inside the loop matters. If bestTwoBack = best ran before robHere were computed, robHere would build on the house right before this one, and neighbours would get robbed together. With the two lines swapped, [1, 2, 3, 1] returns 7, the sum of all four houses, instead of 4.

The original implementation, HouseRobber.java, is on GitHub.

Complexity

The method makes one pass along the street and keeps two running totals.

  • Time: O(n), because the for loop visits each of the n houses once and does one addition and one Math.max at each.
  • Space: O(1), because only best, bestTwoBack and robHere are kept, never a row with one entry per house.

When the houses stand in a circle, so the first and the last are neighbours too, see House Robber II.