#B4220. Maximum Sum of Absolute Differences

    ID: 11877 Type: Default 1000ms 256MiB

Maximum Sum of Absolute Differences

Maximum Sum of Absolute Differences

You are given n cards, with numbers written on them. The number on the i-th card is \(a_i\). Your task is to shuffle the cards to maximize the sum of the absolute differences between consecutive cards. In other words, if after shuffling the sequence of numbers becomes \(b_1, b_2, \dots, b_n\), you need to maximize the quantity

S=i=1n1bi+1bi.S = \sum_{i=1}^{n-1} \left|b_{i+1} - b_i\right|.

For example, suppose there are 4 cards with numbers \([1, 2, 3, 4]\). The sum for the order \([4, 3, 2, 1]\) is 43+32+21=1+1+1=3,|4-3| + |3-2| + |2-1| = 1+1+1 = 3,

while for the order ([2, 4, 1, 3]) it is

42+41+31=2+3+2=7.|4-2| + |4-1| + |3-1| = 2+3+2 = 7.

Since (7 > 3), the order ([2, 4, 1, 3]) is considered "more shuffled". You need to compute the maximum value of (S) over all possible orders.

inputFormat

The first line contains a single integer \(n\) (the number of cards). The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) representing the numbers on the cards.

It is guaranteed that \(n\) is small enough to allow a solution that checks all permutations.

outputFormat

Output a single integer — the maximum possible sum \(S = \sum_{i=1}^{n-1} |b_{i+1} - b_i|\) that can be achieved by reordering the cards.

sample

4
1 2 3 4
7