module S = Set.Make (struct type t = int let compare (a:int) (b:int) = compare a b end)

let () =
    let split s =
        let rec loop i cur flag acc =
            if i = String.length s then ( if flag then cur :: acc else acc) else ( match flag, s.[i] with
                | true,  ' ' -> loop (i + 1) "" false (cur :: acc)
                | false, ' ' -> loop (i + 1) "" false acc
                | true,  v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
                | false, v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
            )
        in
        List.map int_of_string (List.rev (loop 0 "" false []))
    in
    let main () =
        let n = int_of_string (read_line ()) in
        let p = Array.of_list (split (read_line ())) in
        let rev = Array.make n 0 in
        Array.iteri (fun i v -> rev.(v - 1) <- i) p;
        let rec loop i set acc =
            if i < 0 then acc else
                let left, _, right = S.split (rev.(i) * 2) set in
                let l0 = S.max_elt left in
                let l1 = S.max_elt (S.remove l0 left) / 2 in
                let r0 = S.min_elt right in
                let r1 = S.min_elt (S.remove r0 right) / 2 in
                let l0 = l0 / 2 in
                let r0 = r0 / 2 in
                let acc = acc + ((r1 - r0) * (rev.(i) - l0) + (l0 - l1) * (r0 - rev.(i))) * (i + 1) in
                let set = S.add (rev.(i) * 2) set in
                loop (i - 1) set acc
        in
        let r = loop (n - 1) (S.of_list [-2; -3; n * 2; n * 2 + 1]) 0 in
        Printf.printf "%d\n" r
    in
    main ()