← 返回 amazon 的题目列表Minimum Redistribution Cost in Circular Warehouses
类型:online_judge
Problem: Minimum Redistribution Cost in Circular Warehouses
There are n warehouses arranged in a circle, indexed from 0 to n - 1. Warehouse i initially contains products[i] products.
You need to redistribute the products so that every warehouse contains the same number of products. Moving one product across one edge costs 1.
During the entire redistribution process, you must choose exactly one fixed direction:
Clockwise: 0 -> 1 -> 2 -> ... -> n - 1 -> 0
Or counter-clockwise: 0 -> n - 1 -> ... -> 1 -> 0
Different products are not allowed to independently choose their shortest paths. All moved products must follow the same chosen direction.
Return the minimum cost required to make all warehouses have equal product counts. If the total number of products is not divisible by n, return -1.
Input Format
n
products[0] products[1] ... products[n-1]
Output Format
minimum_cost
Constraints
1 <= n <= 2 * 10^5
0 <= products[i] <= 10^9
The answer may exceed 32-bit integer range.
Example
Input:
5
1 11 1 1 1
Output:
20
Explanation: each warehouse should finally contain 3 products. Warehouse 1 has 8 extra products. If all products move clockwise, it sends 2 products to each of the following four warehouses, so the cost is:
2*1 + 2*2 + 2*3 + 2*4 = 20
Example
Input
5
1 11 1 1 1
Output
20