Problem · Array

Find Minimum Cost

HardAmazonNEW GRADFULLTIMEOA
See Amazon hiring insights

There are n containers arranged in a circle. Container i initially contains products[i] products.

Redistribute products so every container contains the same number of products. Moving one product across one edge costs 1.

For the entire redistribution process, choose one global direction, either clockwise or counter-clockwise. Every product that is moved must travel only in that chosen direction around the circle. Products cannot independently choose shorter paths in the opposite direction. For example, if clockwise is chosen, moving a product from position 3 to position 2 costs n - 1, not 1.

Return the minimum total movement cost over the two possible global directions.

Examples
01 · Example 1
products = [3, 4, 6, 6, 6]
return = 7
Example 1 illustration
🌷 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 and move anti-clockwise. Collect one product each from the 5th, 4th, and 3rd positions. Transfer the products 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.
02 · Example 2
products = [1, 11, 1, 1, 1]
return = 20

The final average is 3. Container 1 has 8 extra products. Moving clockwise, send 2 products to each of the next four containers, for 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
sign in to submit