Single-direction stock rebalancing on a ring

0
Sign in

A company keeps stock in n depots placed around a ring. Depot i is joined to depot (i + 1) % n (the clockwise neighbour) and, through the same link, to depot (i - 1 + n) % n. Depot i starts with products[i] units, and the total is a multiple of n.

Move units between neighbouring depots until every depot holds exactly sum(products) / n units. Moving one unit across one link costs 1.

There is one rule: you must pick a single direction for the whole redistribution. Either every unit travels clockwise (from i toward i + 1), or every unit travels counterclockwise (from i toward i - 1). A unit may cross several links.

Implement:

def min_redistribution_cost(products: list[int]) -> int: ...

Return the minimum total cost over the two allowed directions.

Constraints

  • 1 <= n <= 10^5
  • 0 <= products[i] <= 10^9
  • sum(products) is divisible by n

Example 1

products = [5, 1, 3]        # target 3 each

Clockwise: depot 0 sends 2 units to depot 1. Cost 2. Counterclockwise: depot 0 must send its 2 extra units the long way round (0 -> 2 -> 1), and depot 2 passes them on, cost 4. Answer: 2.

Example 2

products = [6, 0, 0, 2]     # target 2 each

Clockwise: depot 0 sends 4 units to depot 1, which keeps 2 and passes 2 to depot 2. Cost 4 + 2 = 6. Counterclockwise costs 10. Answer: 6.

Reconstructed from the reported question; details may differ from what interviewers ask.

AmazonOnline assessmentMediumLast asked Jun 2026

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.