DSA Factory
Free Timed practice lessonsTimed practice · Stage 1 · Timed set 2 · Step 2

Ring of houses

Rob houses around a circle with no two neighbours, where the first and last are neighbours too. About 12 minutes.

What changes on a ring?

On a straight row you chose, house by house, to rob it or skip it, never robbing two neighbours. On a ring, the last house sits next to the first, so you can never rob both of them.

Here is the useful question: if you know for sure the first house is skipped, what kind of problem is left? And what if you know the last one is skipped? Can the ring become rows you already know how to solve?

Break the ring: into straight rows, then use what you know.
Houses worth 6, 2, 7, 3, 8 around a ring · no two neighbours, and the first and last are neighbours
6
0
2
1
7
2
3
3
8
4
fromto
case
both ends possible

On the ring, house 0 and house 4 are neighbours, so you can't rob both. Split into two cases.

Move 1 of 4
Quick check

Why can't you just use the straight-row answer for a ring of houses?

  1. AThe first and last houses are neighbours, so the row answer might rob both
  2. BA ring has more houses than a row
  3. CYou may rob neighbours on a ring
Show the answer

The first and last houses are neighbours, so the row answer might rob both. On a ring every house has two neighbours, and the straight-row plan doesn't know the last touches the first.

Your problem

Ring of houses

Houses stand in a circle, and house i holds nums[i] coins. The first and last houses are neighbours. You may rob any houses, but never two neighbours. Return the largest total you can collect.

Example
nums = [2, 7, 9, 3, 1] → 11

1 ≤ length ≤ 300 · 0 ≤ nums[i] ≤ 1,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve