This page is still under construction.

Parts of this page are still being built. What you see may change.

Sailing Race

Interview

Time limit1sMemory limit128 MB

Summary
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 00. 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 {−3,1,5}\{-3, 1, 5\}, then for the visiting order {−3,1,5}\{-3, 1, 5\} the sum of cumulative distances is 3+(4+3)+(4+7)=213 + (4 + 3) + (4 + 7) = 21 (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.

illustration

As another example, for the signs {−9,−6,−5,−2,1,3,4,10}\{-9, -6, -5, -2, 1, 3, 4, 10\} the visiting order {1,3,4,10,−2,−5,−6,−9}\{1, 3, 4, 10, -2, -5, -6, -9\} gives 1+3+4+10+22+25+26+29=1201 + 3 + 4 + 10 + 22 + 25 + 26 + 29 = 120, while the best order {1,3,4,−2,−5,−6,−9,10}\{1, 3, 4, -2, -5, -6, -9, 10\} gives 1+3+4+10+13+14+17+36=981 + 3 + 4 + 10 + 13 + 14 + 17 + 36 = 98.

Input

The first line contains an integer LL (1≤L≤2001 \le L \le 200), the number of signs to visit, not counting the starting sign.

The second line contains the LL sign positions in increasing order (the starting sign is excluded). Every position is an integer in the range [−700,700][-700, 700].

Output

Print a single positive integer: the minimum sum of cumulative distances over all visiting orders.

Examples4

  1. Example 1

    Input
    8
    -9 -6 -5 -2 1 3 4 10
    
    Expected output
    98
    
  2. Example 2

    Input
    1
    5
    
    Expected output
    5
    
  3. Example 3

    Input
    1
    -7
    
    Expected output
    7
    
  4. Example 4

    Input
    3
    -3 1 5
    
    Expected output
    19