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 Go (1.6) (judge verdict: Accepted)

package main

import (
	"container/list"
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	sort.Ints(a)

	l := list.New()
	for i := 0; i < n; i++ {
		l.PushBack(a[i])
	}

	bb := list.New()
	bb.PushBack((l.Front().Value).(int))
	bb.PushBack((l.Back().Value).(int))
	l.Remove(l.Front())
	l.Remove(l.Back())
	for i := 1; i < n-1; i++ {
		e1 := l.Front()
		e2 := l.Back()
		x1 := e1.Value.(int)
		x2 := e2.Value.(int)

		left := bb.Front().Value.(int)
		right := bb.Back().Value.(int)
		m1 := max(abs(left-x1), abs(right-x1))
		m2 := max(abs(left-x2), abs(right-x2))

		var x int
		var e *list.Element
		if m1 > m2 {
			x, e = x1, e1
		} else {
			x, e = x2, e2
		}
		l.Remove(e)

		if abs(left-x) < abs(right-x) {
			bb.PushBack(x)
		} else {
			bb.PushFront(x)
		}
	}

	vs := make([]int, n)
	i := 0
	for e := bb.Front(); e != nil; e = e.Next() {
		vs[i] = e.Value.(int)
		i++
	}

	ans := 0
	for i := 0; i < n-1; i++ {
		ans += abs(vs[i] - vs[i+1])
	}
	fmt.Println(ans)
}

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}