Problem · Array

Minimum Circular Redistribution Cost

Learn this problem
HardAmazonNEW GRADFULLTIMEOA
See Amazon hiring insights

Problem statement

A warehouse has n identical containers arranged in a circle. Adjacent containers are one unit apart, and the goal is to make every container hold the same number of products.

  • Choose either clockwise or counterclockwise movement; all transfers must use that same direction.
  • Products may be collected from containers with excess units and delivered to containers with deficits.
  • Moving one product across one edge costs 1.

Return the minimum total transfer cost. It is guaranteed that equal redistribution is possible.

Function

findMinimumCost(products: int[]) → long

Examples

Example 1

products = [3, 4, 6, 6, 6]return = 7

Consider a circular arrangement of containers. The units in each container are products = [3, 4, 6, 6, 6].

Position 1 Position 2 Position 3 Position 4 Position 5 3 Products 4 Products 6 Products 6 Products 6 Products

Option 1:

Start at the 3rd position and move clockwise. Collect one product each from the 3rd, 4th, and 5th positions.

Transfer the products from:

  • the 5th position to the 1st position, the cost is 1.
  • the 4th position to the 1st position, the cost is 2.
  • the 3rd position to the 2nd position, the cost is 4.

Now each container has 5 units and the total cost is 1 + 2 + 4 = 7.

Option 2:

Start at the 5th position moving anti-clockwise. Collect one product each from the 5th, 4th, and 3rd positions.

Transfer the product from:

  • the 3rd position to the 1st position, the cost is 2.
  • the 4th position to the 1st position, the cost is 3.
  • the 5th position to the 2nd position, the cost is 3.

Now each container has 5 units and the total cost is 2 + 3 + 3 = 8. Return 7, the minimum cost achievable.

Example 2

products = [1, 11, 1, 1, 1]return = 20

The final average is 3. One container has 8 extra products. Moving in either fixed direction, send 2 products to each of the other four containers, for total cost 2*1 + 2*2 + 2*3 + 2*4 = 20.

Constraints

  • 1 <= products.length <= 2 * 10^5
  • 0 <= products[i] <= 10^9
  • The answer may exceed the 32-bit integer range.

More Amazon problems

drafts saved locally
public long findMinimumCost(int[] products) {
  // write your code here
}
products[3, 4, 6, 6, 6]
expected7
checking account