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 Haskell (GHC 7.10.3) (judge verdict: Accepted)

module Main where

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.List
import qualified Data.ByteString.Lazy.Char8 as L

type Tokenizer = State [L.ByteString]

expand0 :: [Int] -> [Int]
expand0 [] = [1]
expand0 [1] = [-1, 1]
expand0 (x:xs) = (-x:2 * x:xs)

gen0, gen1 :: Int -> [Int]
gen0 n = (iterate expand0 []) !! n

gen1 1 = [1]
gen1 n = map negate $ gen0 n

solve_01 :: [Int] -> (Int -> [Int]) -> Int
solve_01 vs gen = sum $ zipWith (*) vs' cs'
    where vs' = sort vs
          cs' = sort . gen $ length vs

solve :: [Int] -> Int
solve vs = max (solve_01 vs gen0) (solve_01 vs gen1)

nextInt :: Tokenizer Int
nextInt = state $ \(s:ss) -> case L.readInt s of
                               Just (x, _) -> (x, ss)
                               Nothing -> error $ "Can't parse Int from " ++ L.unpack s

go :: Tokenizer Int
go = do
  n <- nextInt
  vs <- replicateM n nextInt
  return $ solve vs
  

main :: IO ()
main = do
  input <- L.words <$> L.getContents
  let answer = evalState go input
  print answer