House Robber II
Rob houses that stand in a circle, never two neighbours, by solving two straight streets and keeping the better one.
Houses stand in a circle, so the first house is next to the last one. Given an array nums
Example 1
Output: 3
Explanation: houses 0 and 2 are neighbours in the circle, so rob only house 1.
Example 2
Output: 4
Explanation: rob house 0 (1) and house 2 (3).
Example 3
Output: 3
Explanation: every two of the three houses are neighbours, so rob house 2 alone.
The Idea
Picture houses built around a small round square, each one touching the next, until the last house touches the first again. Example 1 has three such houses, holding 2, 3 and 2. On a straight street a thief would take both 2s, one at each end, for 4. In the circle, house 0 and house 2 stand side by side, so that plan robs two neighbours. The best allowed plan is house 1 alone, with 3.
So the circle adds one rule to
Look at any allowed plan. It never robs both ends, so it leaves out house 0, or the last house, or both. A plan that leaves out the last house is simply a plan for the straight street from house 0 to the second-to-last house. A plan that leaves out house 0 is a plan for the straight street from house 1 to the last house. Neither street contains both ends, so the circle rule cannot be broken on either.
Each straight street is then solved the way House Robber solves it. Walk along the street and, at each house, write down the most money so far: the most that can be taken from the street's first house up to and including this one. Look at the picture below, which does this for Example 2.
On the left, the four houses of [1, 2, 3, 1]
So a circle of houses becomes two straight streets, and the better of their two results is the answer. Filling in the most money so far house by house, where each value is built from the two values just to its left, is called dynamic programming.
Solution Approach
Turning that idea into code means settling three things: filling in one street without trying every choice of houses, handing both streets to the same code, and handling a circle of one house.
The most money so far on one street
How is the most money so far at one house worked out from the houses before it? At each house the thief either robs it or walks past. Robbing it means the house before was skipped, so the total is this house's money plus the most money so far two houses back. Walking past keeps the most money so far at the house before. The most money so far is the larger of the two.
Check it on the row labelled "without the last house" in the picture. At house 2, robbing gives 3 + 1 = 4, and walking past gives 2, so the most money so far there is 4.
The slow way tries every set of houses and throws out the sets that contain neighbours. That works, but 30 houses already give 230 sets, over a billion, to sort through. Filling in the row needs one step per house instead.
Each value needs only the two values before it, so the whole row does not have to be kept. Two variables are enough: the most money so far at the house before, and at the house two back.
Handing both streets to the same code
How does one piece of code solve both streets? Both are stretches of the same array, so a helper method takes the array plus the first and last position of its stretch. With n houses, positions 0 to n - 2 leave out the last house, and positions 1 to n - 1 leave out house 0. The array itself is never copied.
A circle of one house
What if there is just one house? It has no neighbour, so the thief takes its money. Both stretches, though, would be empty: 0 to -1 and 1 to 0. They would give 0, so the method returns nums[0]
Java Solution
The method rob
- First, store the number of houses in
. Ifn is 1, returnn right away, since a single house has no neighbour.nums[0] - Otherwise, use a helper,
, which takes the array plus the first and last position of a street, namedrobLine andfrom . Call it twice:to for the street without the last house androbLine(nums, 0, n - 2) for the street without the first. Return the larger result withrobLine(nums, 1, n - 1) .Math.max - Inside
, two variables start at 0:robLine holds the most money so far up to the house before, andbest holds it up to two houses back.skipLast - A loop moves
from positioni to positionfrom . At each house,to isrobHere , the total if this house is robbed. ThenskipLast + nums[i] takes the oldskipLast , andbest becomes the larger ofbest andbest .robHere - When the loop ends,
is the most money for the whole street, andbest returns it.robLine
The main[2, 7, 9, 3, 1]robLine
public class HouseRobber2 {
public static int rob(int[] nums) {
int n = nums.length;
if (n == 1) {
return nums[0];
}
// The first and last houses are neighbours: leave out one of them.
return Math.max(robLine(nums, 0, n - 2), robLine(nums, 1, n - 1));
}
// Plain House Robber on the straight street nums[from..to], to included.
private static int robLine(int[] nums, int from, int to) {
int skipLast = 0; // best total up to two houses back
int best = 0; // best total up to the previous house
for (int i = from; i <= to; i++) {
int robHere = skipLast + nums[i];
skipLast = best;
best = Math.max(best, robHere);
}
return best;
}
public static void main(String[] args) {
System.out.println(rob(new int[] {2, 3, 2}));
System.out.println(rob(new int[] {1, 2, 3, 1}));
System.out.println(rob(new int[] {1, 2, 3}));
System.out.println(rob(new int[] {5}));
System.out.println(rob(new int[] {4, 9}));
System.out.println(rob(new int[] {2, 7, 9, 3, 1}));
int[] ring = {2, 3, 2};
System.out.println("whole circle as a street: " + robLine(ring, 0, ring.length - 1));
}
}
Running it prints:
3
4
3
5
9
11
whole circle as a street: 4
Example 1 gives 3, house 1 alone, and Example 2 gives 4, the end value of the row labelled "without the last house" in the picture. The single house [5]n == 1[4, 9]
Look at the line with 11, from [2, 7, 9, 3, 1]
The last line shows what goes wrong if the circle is treated as one straight street. Example 1 comes out as 4, from robbing house 0 and house 2, which are neighbours in the circle.
The original implementation,
Complexity
The work is two walks along the houses, with a few additions and comparisons at each house.
- Time: O(n), because each of the two
calls walks n - 1 of the n houses, doing one addition and one comparison at each.robLine - Space: O(1), because each
call keeps onlyrobLine ,best andskipLast , and the two streets are given as positions inrobHere , not copied arrays.nums
Breaking a circle into two straight cases also solves