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 with the money in each house, in order around the circle, return the most money a thief can take without robbing two houses that are next to each other. The array holds at least one house. Apart from the circle, this is the same problem as House Robber.

Example 1
Input: nums = [2, 3, 2]
Output: 3
Explanation: houses 0 and 2 are neighbours in the circle, so rob only house 1.
Example 2
Input: nums = [1, 2, 3, 1]
Output: 4
Explanation: rob house 0 (1) and house 2 (3).
Example 3
Input: nums = [1, 2, 3]
Output: 3
Explanation: every two of the three houses are neighbours, so rob house 2 alone.
Solution

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 House Robber: house 0 and the last house may not both be robbed. Every other pair of neighbours is the same as on a straight street. How can we respect that one extra rule without inventing a whole new solution?

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.

The houses of [1, 2, 3, 1] stand in a circle, and house 0 and house 3 are neighbours. Without the last house, houses 0 to 2 give most money so far 1, 2, 4. Without the first house, houses 1 to 3 give 2, 3, 3. The answer is the larger of 4 and 3, which is 4.

On the left, the four houses of [1, 2, 3, 1] stand in a circle, and the orange arc marks house 0 and house 3 as neighbours. The row labelled "without the last house" covers houses 0 to 2, and its most money so far grows 1, 2, 4. That last 4 is house 0 plus house 2. The row labelled "without the first house" covers houses 1 to 3 and ends at 3. The answer is the larger end value, 4.

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] before building them. With two houses, each stretch holds one house, and the larger amount wins.

Java Solution

The method rob works in these steps:

  1. First, store the number of houses in n. If n is 1, return nums[0] right away, since a single house has no neighbour.
  2. Otherwise, use a helper, robLine, which takes the array plus the first and last position of a street, named from and to. Call it twice: robLine(nums, 0, n - 2) for the street without the last house and robLine(nums, 1, n - 1) for the street without the first. Return the larger result with Math.max.
  3. Inside robLine, two variables start at 0: best holds the most money so far up to the house before, and skipLast holds it up to two houses back.
  4. A loop moves i from position from to position to. At each house, robHere is skipLast + nums[i], the total if this house is robbed. Then skipLast takes the old best, and best becomes the larger of best and robHere.
  5. When the loop ends, best is the most money for the whole street, and robLine returns it.

The main method runs the three examples, one house, two houses, and [2, 7, 9, 3, 1], where the circle rule changes the answer. Its last line runs robLine on the whole circle of Example 1, as if it were a straight street.

Java
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:

Output
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] prints 5 because of the n == 1 check. Without that check, both stretches are empty and the same input prints 0. For [4, 9], each stretch holds one house, and 9 wins.

Look at the line with 11, from [2, 7, 9, 3, 1]. On a straight street the best is 2 + 9 + 1 = 12, but house 0 and house 4 are neighbours in the circle. Leaving out the last house gives 2 + 9 = 11, and leaving out the first gives 7 + 3 = 10, so the answer is 11.

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, HouseRobber2.java, is on GitHub.

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 robLine calls walks n - 1 of the n houses, doing one addition and one comparison at each.
  • Space: O(1), because each robLine call keeps only best, skipLast and robHere, and the two streets are given as positions in nums, not copied arrays.

Breaking a circle into two straight cases also solves Maximum Sum Circular Subarray.