Stalls Around the Roundabout

Medium · 1-D Dynamic Programming · about 20 min

Food stalls stand in a circle around a roundabout. Stall i will donate values[i] to your charity drive, but two stalls that stand next to each other will not both donate. Stall 0 and the last stall are next to each other, because the stalls form a circle.

Return the largest total you can collect.

  • 0 <= len(values) <= 1000, each value is between 0 and 1000.
  • With one stall, it has no neighbour, so you can take it. With no stalls the answer is 0.

Examples:

ring_collect([2, 3, 2]) → 3 (the two 2s are neighbours across the circle)

ring_collect([1, 2, 3, 1]) → 4 (1 + 3)

Hints

  • First solve it for stalls in a straight line: at each stall, either skip it or take it plus the best from two stalls back.
  • In a circle, the first and the last stall are never both taken. So at least one of them is left out.
  • Run the line version twice, once without the first stall and once without the last, and keep the larger result. Check the one-stall case.

Learn the pattern first: the 1-D Dynamic Programming lesson.

More 1-D Dynamic Programming problems