The directional constraint is what makes this hard.
First, recognize that the target amount per warehouse is the average. Then, compute the net surplus or deficit at each position and use prefix sums to determine the cumulative flow across each edge. The minimum cost is the sum of the absolute values of these cumulative flows, but since all moves must be in one direction, we need to adjust by subtracting the median of the prefix sums to minimize the total cost.
Pro tip: Clarify that the one-direction constraint means we cannot simply take the sum of absolute prefix sums; instead, we must shift all flows by a constant (the median) to ensure non-negativity. This is a key nuance that many candidates miss.
Calculate the average number of products per warehouse, which is the total divided by n. This is the goal for each position.
For each warehouse, compute the difference between its current amount and the target. Positive means surplus, negative means deficit.
Traverse the circle in the fixed direction and compute the cumulative sum of surpluses/deficits. These prefix sums represent the net flow that must cross each edge if we only move in that direction.
Since all moves must be in one direction, the flows cannot be negative. Find the median of the prefix sums and subtract it from each prefix sum to get the actual non-negative flows.
The minimum cost is the sum of the absolute values of the adjusted prefix sums. This gives the total number of product moves needed.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.