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;
typedef long long LL;
const int maxn=2e5+100;
LL a[maxn];
int n;
bool cmp(const LL x,const LL y){
    return x>y;
}
int main()
{
    //freopen("in.txt","r",stdin);
    scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
    sort(a+1,a+1+n,cmp);
    vector<LL>b;
    int i=1,j=n;
    while(i<j){
        b.push_back(a[i]);
        b.push_back(a[j]);
        i++,j--;
    }
    if(n%2){
        b.push_back(a[(n+1)/2]);
    }
    LL sum1=0;
    for(int i=1;i<b.size();i++){
        sum1+=abs(b[i]-b[i-1]);
    }
    int len=b.size()-1;
    LL sum=abs(b[0]-b[len]);
   // cout<<sum<<endl;
    for(int i=1;i<len;i++){
        sum+=abs(b[i]-b[i-1]);
    }
    LL sum2=0;
    for(int i=1;i<len;i++){
        sum2+=abs(b[i]-b[i-1]);
    }
    sort(a+1,a+1+n);
    vector<LL>c;

    i=1,j=n;
    while(i<j){
        c.push_back(a[i]);
        c.push_back(a[j]);
        i++,j--;
    }
    if(n%2){
        c.push_back(a[(n+1)/2]);
    }
    LL sum3=0;
    for(int i=1;i<c.size();i++){
        sum3+=abs(c[i]-c[i-1]);
    }
    len=c.size()-1;
    LL sum4=abs(c[0]-c[len]);
   // cout<<sum<<endl;
    for(int i=1;i<len;i++){
        sum4+=abs(c[i]-c[i-1]);
    }
    LL num=max(sum3,sum4);
    LL num1=max(sum,sum1);
    printf("%lld\n",max(num,num1));
    return 0;
}