AmazonOA #295
Minimize Warehouse Transfer Cost
Estimated MediumJudge-ready
Topics (AI-labelled)Prefix & RangesGreedy
n warehouses form a ring, and moving one item across an adjacent edge costs 1. The goal is for every warehouse to end up with the same number of items; the total is guaranteed to be divisible by n. The whole plan must use only one direction, either clockwise or counterclockwise, and cannot mix directions; you may choose any starting point. Find the minimum total cost.
Input
The first line contains n and the second line contains warehouses. On this site 1≤n≤200000, 0≤warehouses[i]≤10^9, and sum%n=0 is guaranteed. Output the exact integer cost, without any modulus.
Output
Output a single integer, the answer.
Example 1
Input:
4
0 4 4 0
Output:
8
Example 2
Input:
5
3 4 6 6 6
Output:
7
Example 3
Input:
2
1 1
Output:
0
Example notes
The answers are 8, 7 and 0 respectively. In the first example, moving items in both directions could cost 4, but the original rule of a single direction throughout makes the minimum 8.
Editorial
Loading solution…