AmazonOA #53
Minimize Variation
Estimated HardJudge-ready
Topics (AI-labelled)Tree & Game DPIn-place Arrays
Rearrange the array, compute the maximum minus the minimum of every non-empty prefix, and add these ranges together. Find the minimum total.
Input
The first line contains n (1..2000), and the second line contains n values (1..10⁹).
Output
Output a single integer answer.
Example 1
Input:
3
3 1 2
Output:
3
Example 2
Input:
1
7
Output:
0
Example 3
Input:
3
1 1 5
Output:
4
Example notes
Example 1: the order 1, 2, 3 has prefix ranges 0, 1, 2, for a total of 3. Example 2: there is only one value, range 0. Example 3: place the two 1s first and then 5, giving ranges 0, 0, 4, for a total of 4.
Editorial
Loading solution…