Sailing Race
InterviewTime limit1sMemory limit128 MB
Given sign positions on a line, find the visiting order minimizing the sum of cumulative distances, where each next sign adds the distance from the previous sign.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Greedy, Sorting, Intervals
- Solved
- No attempts yet
Problem
For an upcoming sailing cup, the organizing committee designed a new race to make it more challenging. A number of floating signs are placed along a straight line at various distances in the sea. All boats start at the same time from one specific point on this line and must visit every sign. A boat's race ends once it has visited all signs. To win, a boat must visit every sign while covering the minimum sum of cumulative distances.
The cumulative distance of the first visited sign equals that sign's distance from the starting point. The cumulative distance of every later sign equals the distance from the previously visited sign plus the cumulative distance of that previous sign.
The starting sign is labeled . Signs to the right of the start are labeled with positive integers equal to their distance from the start, and signs to the left with negative integers. For example, if the signs are at positions , then for the visiting order the sum of cumulative distances is (this shows how the metric is computed for one particular order; it is not necessarily the minimum).
Your task is to read the sign positions and output the minimum possible sum of cumulative distances over all visiting orders.

As another example, for the signs the visiting order gives , while the best order gives .
Input
The first line contains an integer (), the number of signs to visit, not counting the starting sign.
The second line contains the sign positions in increasing order (the starting sign is excluded). Every position is an integer in the range .
Output
Print a single positive integer: the minimum sum of cumulative distances over all visiting orders.