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: Time Limit Exceeded)

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

typedef long long ll;
typedef pair<int,int> pii;

int read(){
	int xx=0,ww=1;
	char ch=getchar();
	while(ch>'9'||ch<'0'){
		if(ch=='-') ww=-ww;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9'){
		xx=10*xx+ch-48;
		ch=getchar();
	}
	return xx*ww;
}

int n;
int a[1000001];
ll ans=0;
vector<pair<int,pii> >ed;
int used[1000001];
int fa[1000001];

int find_set(int x) {
	if(fa[x]!=x) fa[x]=find_set(fa[x]);
	return fa[x];
}

bool cmp(pair<int,pii>a,pair<int,pii>b) {
	return a.second.second>b.second.second;
}

ll kru() {
	sort(ed.begin(),ed.end(),cmp);
//	for(int i=0;i<ed.size();i++) if(ed[i].second.second>0) cout<<ed[i].first<<' '<<ed[i].second.first<<' '<<ed[i].second.second<<endl;
	for(int i=1; i<=n; i++) fa[i]=i;
	int cnt=0;
	for(int i=0; i<ed.size(); i++) {
		used[ed[i].first]++;
		used[ed[i].second.first]++;
		if(used[ed[i].second.first]>2||used[ed[i].first]>2) {
			used[ed[i].first]--;
			used[ed[i].second.first]--;
			continue;
		}
		int fata=find_set(ed[i].first),fatb=find_set(ed[i].second.first);
		if(fata==fatb) {
			used[ed[i].first]--;
			used[ed[i].second.first]--;
			continue;
		} else {
			fa[fata]=fatb;
			cnt++;
			ans+=(ll)ed[i].second.second;
			if(cnt==n-1) break;
		}
	}
	return ans;
}

int main() {
	freopen("ii.txt","r",stdin);
	n=read();
	for(int i=1; i<=n; i++) a[i]=read();
//	sort(a+1,a+n);
	if(n<=1000) {
		for(int i=1; i<n; i++)
			for(int j=i+1; j<=n; j++)
				ed.push_back(make_pair(i,make_pair(j,abs(a[i]-a[j]))));
	} else {
		for(int i=1; i<n; i++)
			for(int j=min(n,n-i+5); j>=max(1,n-i-5); --j)
				ed.push_back(make_pair(i,make_pair(j,abs(a[i]-a[j]))));
	}
	cout<<kru()<<endl;
	return 0;
}