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 C++14 (GCC 5.4.1) (judge verdict: Accepted)

#include <bits/stdc++.h>
using namespace std;

#define N 100010
#define ll long long
int n;
ll arr[N], res, tmp, a, b; 
int l, r;

void work(int cnt)
{
	for (; ; cnt ^= 1)
	{
		if (l > r) return;
		if (l == r) 
		{
			tmp += max(abs(arr[l] - a), abs(arr[l] - b));
			return;
		}
		if (cnt == 0)
		{
			tmp += abs(arr[l] + arr[l + 1] - a - b);
			a = arr[l], b = arr[l + 1]; 
			l += 2;
		}
		else
		{
			tmp += abs(arr[r] + arr[r - 1] - a - b);
			a = arr[r], b = arr[r - 1];
			r -= 2;
		}
	}
}

int main()
{
	while (scanf("%d", &n) != EOF)
	{	
		res = 0;
		for (int i = 1; i <= n; ++i) scanf("%lld", arr + i);
		if (n == 1) puts("0");
		else if (n == 2) printf("%lld\n", abs(arr[1] - arr[2]));
		else
		{
			sort(arr + 1, arr + 1 + n);
			tmp = arr[n - 1] + arr[n] - 2 * arr[1];
			a = arr[n - 1], b = arr[n];
			l = 2, r = n - 2; 	
			work(0); 
			res = max(res, tmp); 
			tmp = 2 * arr[n] - arr[1] - arr[2];
			a = arr[1], b = arr[2];
			l = 3, r = n - 1;
			work(1);
			res = max(res, tmp);
			printf("%lld\n", res);
		
		}
	}
	return 0;
}