Scanf.scanf "%d" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
    Array.sort compare a;

    let rec check v1 v2 lp rp sum =
        if lp > rp then sum else
            let q = [| abs (v1 - a.(lp)), 0;
                       abs (v2 - a.(lp)), 1;
                       abs (v1 - a.(rp)), 2;
                       abs (v2 - a.(rp)), 3 |]
            in
            Array.sort compare q;
            match q.(3) with
            | v, 0 -> check a.(lp) v2     (lp + 1) rp       (sum + v)
            | v, 1 -> check v1     a.(lp) (lp + 1) rp       (sum + v)
            | v, 2 -> check a.(rp) v2     lp       (rp - 1) (sum + v)
            | v, _ -> check v1     a.(rp) lp       (rp - 1) (sum + v)
    in
    max (check a.(0) a.(0) 1 (n - 1) 0) (check a.(n - 1) a.(n - 1) 0 (n - 2) 0) |> Printf.printf "%d\n"
)