0:00 / 0:00

Rob houses in a circle without hitting two neighbours. The first and last touch, so run House Robber twice: once without each end.

▼

The problem

LeetCode 213 (Medium). Houses stand in a circle, so the first and the last house are neighbours; nums[i] is the cash in house i. Robbing two neighbouring houses sets off the alarm. Return the most you can rob.

Example: episode one's street [2, 7, 9, 3, 1], bent into a ring.

TRY IT ON LEETCODE ▶

The solution

def rob(nums):
    if len(nums) == 1:
        return nums[0]
    return max(line(nums, 0, len(nums) - 1),
               line(nums, 1, len(nums)))

def line(nums, lo, hi):
    prev, cur = 0, 0
    for i in range(lo, hi):
        prev, cur = cur, max(cur, prev + nums[i])
    return cur

Transcript

House Robber Two. Same rule as episode one: each house holds some cash, and robbing two neighbors sets off the alarm. But now the street is a ring. The first house and the last house are neighbors too. What's the most you can take?

Here is episode one's street, bent into a circle: two, seven, nine, three, one. Five houses, and five pairs of neighbors, because the last house, one, now touches the first, two.

The tempting move is plain House Robber on the whole row. It picks two, nine and one, for twelve. But on the ring, one sits right next to two, so the alarm goes off. Twelve is not allowed. Checking every set of houses would work, but that's two to the n choices.

Here's the fix. The first and last houses can never both be robbed, so one of them always stays untouched. Close the road between them, and break the circle twice: once without the last house, and once without the first. Each is a plain street, which episode one already solves. Keep the bigger haul.

In code, a helper robs a plain street with two running numbers: the best haul up to two houses back, and the best so far. At each house, the best becomes the bigger of skipping it, or its cash plus the haul from two back. The main function keeps the max of both streets. A single house is just its cash.

Let's play two, seven, nine, three, one. Street A drops the last house. Two. Seven beats two. Nine plus two makes eleven. Three plus seven is only ten, so eleven stays. Street B drops the first house. Seven, then nine. Three plus seven makes ten. One plus nine only ties ten. Eleven beats ten, so the answer is eleven: two and nine.

Two passes over the houses, so the time is order n. Each pass keeps just two numbers, so the space is order one.

Break the ring, rob two streets, keep the better haul. That's House Robber Two.