Best haul when the lockers form a ring

Dynamic programming Mid-level Python 3.13+ Reviewed By Best Latest Apps

Pick the fix

Lockers in a ring hold [3, 1, 3]. The row version returns 6. What is wrong?

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A It opens the first and last lockers, which are neighbours in a ring

Right: the true answer is 3.

Dropping one end per run removes exactly the forbidden pair and nothing else.

Why not the others?
  • B Nothing; 6 is correct. Lockers 0 and 2 touch in a ring.
  • C It should return 7, the total. Opening all three breaks the rule twice.

30-second answer

In a ring, the first and last lockers cannot both be opened. So solve the straight-row version twice, once without the first locker and once without the last, and take the better result. Each run is O(n), so the total is O(n) time. The two slices take O(n) memory; passing index bounds instead of slices brings it to O(1).

Practise saying it · 30 s. No recording, just a timer

Explain the ring version.

Say your answer out loud, then check which of these points you covered:

  • First and last are neighbours
  • Run without first, run without last
  • O(n)

Deep dive

Breaking a circular constraint into two straight cases is a reusable trick.

A single locker is a special case: both runs would drop it.

The same split handles circular scheduling and seating questions.

Python solution Ran on Python 3.13.5 · mypy --strict
Python 3.13
def ring_haul(amounts: list[int]) -> int:
    def straight(row: list[int]) -> int:
        two_back = one_back = 0
        for a in row:
            two_back, one_back = one_back, max(one_back, two_back + a)
        return one_back

    if len(amounts) == 1:
        return amounts[0]
    return max(straight(amounts[1:]), straight(amounts[:-1]))

Common mistakes

  • Running the row version once and ignoring the wrap-around.
  • Dropping both the first and the last in the same run, which loses valid answers.

Senior take & follow-ups

Explain why two runs cover every valid choice.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why are two runs enough?

    Show hint

    Any valid choice either skips the first locker or skips the last, so one of the runs covers it.

  2. What about a ring where you must open exactly k lockers?

    Show hint

    Add k to the state: best[i][j] with j lockers opened, still split into two straight cases.

What each operation costs: Two Dimensional Arrays

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.