Skip to content
BytePatterns

House Robber in a Circle

Dynamic Programming: lesson 14 of 20

First and last are now neighbours, so run the line twice.

Lesson 14 of 20 · 5 min

House Robber in a Circle

Step 1 of 10

On a circle house 1 and house 5 are neighbours. So forbid one of them and the problem is a plain line again — twice.

The Idea

On a circle the only new rule is that the first and last houses touch. Rather than invent a recurrence for it, forbid one of them: solve the line without the last house, solve it again without the first, and keep the better. Every legal circular plan misses at least one end, so one of those two runs contains it.

Real-World Example

Ad slots around a rotating carousel, where neighbouring slots may not sell to the same advertiser. The last slot wraps back to the first, so the booking tool prices the strip twice — once ignoring the final slot, once ignoring the opening one.

The Code

def rob_line(vals):
    take, skip = 0, 0
    for v in vals:
        take, skip = skip + v, max(skip, take)   # take v, or keep the best so far
    return max(take, skip)

houses = [2, 7, 9, 3, 1]

print(rob_line(houses))                                     # 12 on a line
print(max(rob_line(houses[:-1]), rob_line(houses[1:])))     # 11 on a circle

Python

Your turn

What does this print?

def rob_line(vals):
  take, skip = 0, 0
  for v in vals:
      take, skip = skip + v, max(skip, take)
  return max(take, skip)

houses = [6, 1, 1, 6]
print(max(rob_line(houses[:-1]), rob_line(houses[1:])))

Mini quiz

1 / 3

Why can the linear solution not be used directly on a circle?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.