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 Scala (2.11.7) (judge verdict: Runtime Error)

object Main extends App {
  val n = readInt
  val ints = (1 to n).map(_ => readInt)
  val (smallerInts, largerInts) = ints.sorted.splitAt(ints.length / 2)
  val zippedInts = largerInts.reverse.zip(smallerInts).flatMap { case (l, s) => Seq(l, s) }
  val lastElemOpt = if (ints.length % 2 == 0) None else Some(largerInts.head)


  case class Hoge(left: Int, right: Int, prevIsRight: Boolean, currentIsRight: Boolean) {
    def last(lastElem: Option[Int]): Option[Long] = lastElem.map(x => math.max(math.abs(left - x), math.abs(right - x)))
  }

  def next(num: Int): State[Hoge, Long] = State({
      case Hoge(l, r, true, true) => (Hoge(num, r, true, false), math.abs(l - num))
      case Hoge(l, r, true, false) => (Hoge(num, r, false, false), math.abs(l - num))
      case Hoge(l, r, false, false) => (Hoge(l, num, false, true), math.abs(r - num))
      case Hoge(l, r, false, true) => (Hoge(l, num, true, true), math.abs(r - num))
    })



  case class State[S, A](run: S => (S, A)) {
    def map[B](f: A => B): State[S, B] = flatMap(a => State.unit(f(a)))

    def flatMap[B](f: A => State[S, B]): State[S, B] = State(s => {
      val (s1, a) = run(s)
      val (s2, b) = f(a).run(s1)
      (s2, b)
    })
  }

  object State {
    def unit[S, A](a: A): State[S, A] = State(s => (s, a))
  }

  implicit class StateOps[S](states: Seq[State[S, Long]]) {
    def sequence: State[S, Long] = states.foldLeft[State[S, Long]](State.unit(0L))((acc, h) => {
      acc.flatMap(a1 => h.map(a2 => a1 + a2))
    })
  }

  val init = Hoge(zippedInts.head, zippedInts.head, false, false)
  val res = zippedInts.tail.map(next(_)).sequence.run(init)
  println(res._1.last(lastElemOpt).getOrElse(0L) + res._2)
}