NewThe Learning module is now liveSee what's new

You have n warehouses arranged in a circle, numbered 0 to n - 1, where warehouse i connects clockwise to warehouse (i + 1) % n. Each warehouse i initially holds products[i] units. It is guaranteed that the sum of all product units is divisible by n. Your goal is to redistribute products so that every warehouse holds the same number of units.

The redistribution must commit to a single direction: either all movements go clockwise or all movements go counterclockwise. Products cannot be routed individually; all movements must follow the same direction. Each time one unit crosses one edge, the cost increases by 1.

Return the minimum total cost over the two direction choices.

Constraints:

  • 1 ≤ n ≤ 10510^5
  • 0 ≤ products[i] ≤ 10410^4

Example 1:

Input: products = [1, 11, 1, 1, 1] Output: 20 Explanation: There are 15 total units across 5 warehouses, so each warehouse should end with 3 units. Compared with the target, warehouse 1 (0-indexed) has 8 extra units, while warehouses 0, 2, 3, and 4 each need 2 units. If we move products clockwise from warehouse 1:

  • Send 2 units to warehouse 2: cost 2 × 1 = 2
  • Send 2 units to warehouse 3: cost 2 × 2 = 4
  • Send 2 units to warehouse 4: cost 2 × 3 = 6
  • Send 2 units to warehouse 0: cost 2 × 4 = 8

The total clockwise cost is 2 + 4 + 6 + 8 = 20. Moving them counterclockwise also costs 20.

Example 2:

Input: products = [7, 0, 0, 0, 3] Output: 13

Example 3:

Input: products = [3, 1, 5, 3, 3, 3] Output: 2


Accepted
172/515
Acceptance Rate33.4%
Test Cases
Input
products =
Output
Expected