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]i
Example 1
Output: 4
Explanation: rob houses 0 and 2: 1 + 3.
Example 2
Output: 12
Explanation: rob houses 0, 2 and 4: 2 + 9 + 1.
Example 3
Output: 4
Explanation: rob houses 0 and 3: 2 + 2.
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]
Taking the biggest amount first fails too. On the street [2, 3, 2]
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 ii
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
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 ii - 1i - 2
What each entry holds
How is one entry worked out? Call the entry for house ibest(i)i
- skip house
:i ;best(i - 1) - rob house
:i , because housebest(i - 2) + nums[i] must then be skipped.i - 1
In one line, best(i) = max(best(i - 1), best(i - 2) + nums[i])
Where the row starts
What do best(0)best(1)best(0)best(1)
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
- First, set up two running totals, both 0.
is the most money from the houses before the current one, andbest the most money from the houses before the previous one. At the start they stand for the empty stretch before house 0.bestTwoBack - Walk along the street with a
loop that takes each house's money asfor .money - Inside the loop, compute
, the total if this house is robbed.robHere = bestTwoBack + money - Move
forward to the oldbestTwoBack , then setbest to the larger ofbest (skip this house) andbest . NowrobHere covers the houses up to this one.best - When the loop has passed every house,
holds the most money from the whole street, and the method returns it.best
The main[2, 3, 2]
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:
[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][2, 1, 1, 2][2, 3, 2]
The last two lines are the smallest streets. [5][]best
The order of the lines inside the loop matters. If bestTwoBack = bestrobHererobHere[1, 2, 3, 1]
The original implementation,
Complexity
The method makes one pass along the street and keeps two running totals.
- Time: O(n), because the
loop visits each of the n houses once and does one addition and onefor at each.Math.max - Space: O(1), because only
,best andbestTwoBack are kept, never a row with one entry per house.robHere
When the houses stand in a circle, so the first and the last are neighbours too, see