AmazonOA #110
Minimize Sum of Distances to Warehouses
Estimated MediumJudge-ready
Topics (AI-labelled)Prefix & RangesIn-place Arrays
Choose any two warehouse positions on the number line; each center goes to its nearer warehouse, and the sum of all centers' distances should be minimized. The warehouses may coincide, and neither is required to serve any center.
Input
The first line contains n, and the second line contains n values dist_centers. The original gives no value ranges; this site sets 1≤n≤200000, −10⁹≤position≤10⁹.
Output
Output a single integer answer.
Example 1
Input:
4
1 2 10 11
Output:
2
Example 2
Input:
1
7
Output:
0
Example 3
Input:
3
0 5 10
Output:
5
Example notes
Example 1: put the warehouses at 1 and 10, for a total distance of 0+1+0+1=2. Example 2: put a warehouse at 7, for a total distance of 0. Example 3: either both ends, or one endpoint together with 5, gives the minimum total distance 5.
Editorial
Loading solution…