Problem:
Score : 400 points

Problem Statement

You are given N integers; the i-th of them is A_i.
Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like.

Constraints

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the maximum possible sum of the absolute differences between the adjacent elements after arranging the given integers in a row in any order you like.

Sample Input 1

5
6
8
1
2
3

Sample Output 1

21

When the integers are arranged as 3,8,1,6,2, the sum of the absolute differences between the adjacent elements is |3 - 8| + |8 - 1| + |1 - 6| + |6 - 2| = 21. This is the maximum possible sum.

Sample Input 2

6
3
1
4
1
5
9

Sample Output 2

25

Sample Input 3

3
5
5
1

Sample Output 3

8

Solution in Python (3.4.3) (judge verdict: Time Limit Exceeded)

def calc(a) :
    sum = 0
    for i in range(len(a) - 1):
        sum += abs(a[i + 1] - a[i])
    return sum

def crossList(a,b):
    y = []
    if len(a) > len(b):
        for i in range(len(b)):
            y.append(a[i])
            y.append(b[i])
        y.append(a[i+1])
    elif len(a) < len(b): 
        for i in range(len(a)):
            y.append(b[i])
            y.append(a[i])
        y.append(b[i+1])
    else :
        for i in range(len(a)):
            y.append(b[i])
            y.append(a[i])
    return y

n = int(input())
a = []
for i in range(n):
    a.append(int(input()))
a.sort()
b = []
c = []
f = []
g = []
if len(a) % 2 == 1:
    b = a[0:int((len(a) - 1)/2) ]
    c = a[int((len(a) - 1)/2) : len(a)]
    f = a[0:int((len(a) - 1)/2) + 1]
    g = a[int((len(a) - 1)/2) + 1 : len(a)]
else :
    b = a[0:int((len(a) - 1)/2) + 1 ]
    c = a[int((len(a) - 1)/2) + 1: len(a)]
c.reverse()
g.reverse()
d = []
e = []
h = []
j = []
forward = True;
for i in range(len(b)):
    if forward:
        d.append(b[i])
    else :
        d.reverse()
        d.append(b[i])
        d.reverse()
    forward = not forward
forward = True
for i in range(len(c)):
    if forward:
        e.append(c[i])
    else :
        e.reverse()
        e.append(c[i])
        e.reverse()
    forward = not forward
forward = True
for i in range(len(f)):
    if forward:
        h.append(f[i])
    else :
        h.reverse()
        h.append(f[i])
        h.reverse()    
    forward = not forward
forward = True
for i in range(len(g)):
    if forward:
        j.append(g[i])
    else :
        j.reverse()
        j.append(g[i])
        j.reverse()
    forward = not forward
print(max(calc(crossList(d,e)),calc(crossList(d[::-1],e[::-1])),
          calc(crossList(d,e[::-1])),calc(crossList(d[::-1],e)),
          calc(crossList(h[::-1],j[::-1])),calc(crossList(h,j[::-1])),
          calc(crossList(h[::-1],j)),calc(crossList(h,j))))