CF BUDDY
← Problems·

1509C · The Sports Festival

1800 · dp, greedy

Problem: The student council is preparing for the relay race at the sports festival.

The council consists of nn members. They will run one after the other in the race, the speed of member ii is sis_i. The discrepancy did_i of the ii-th stage is the difference between the maximum and the minimum running speed among the first ii members who ran. Formally, if aia_i denotes the speed of the ii-th member who participated in the race, then di=max(a1,a2,,ai)min(a1,a2,,ai)d_i = \max(a_1, a_2, \dots, a_i) - \min(a_1, a_2, \dots, a_i).

You want to minimize the sum of the discrepancies d1+d2++dnd_1 + d_2 + \dots + d_n. To do this, you are allowed to change the order in which the members run. What is the minimum possible sum that can be achieved?

Input Format: The first line contains a single integer nn (1n20001 \le n \le 2000)  — the number of members of the student council.

The second line contains nn integers s1,s2,,sns_1, s_2, \dots, s_n (1si1091 \le s_i \le 10^9)  – the running speeds of the members.

Output Format: Print a single integer  — the minimum possible value of d1+d2++dnd_1 + d_2 + \dots + d_n after choosing the order of the members.

Note: In the first test case, we may choose to make the third member run first, followed by the first member, and finally the second. Thus a1=2a_1 = 2, a2=3a_2 = 3, and a3=1a_3 = 1. We have:

  • d1=max(2)min(2)=22=0d_1 = \max(2) - \min(2) = 2 - 2 = 0.
  • d2=max(2,3)min(2,3)=32=1d_2 = \max(2, 3) - \min(2, 3) = 3 - 2 = 1.
  • d3=max(2,3,1)min(2,3,1)=31=2d_3 = \max(2, 3, 1) - \min(2, 3, 1) = 3 - 1 = 2.

The resulting sum is d1+d2+d3=0+1+2=3d_1 + d_2 + d_3 = 0 + 1 + 2 = 3. It can be shown that it is impossible to achieve a smaller value.

In the second test case, the only possible rearrangement gives d1=0d_1 = 0, so the minimum possible result is 00.

Sample Cases

Case 1

Input

3
3 1 2

Output

3

Case 2

Input

1
5

Output

0

Case 3

Input

6
1 6 3 3 6 3

Output

11

Case 4

Input

6
104 943872923 6589 889921234 1000000000 69

Output

2833800505

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback