module simple;import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, std.bitmanip, core.stdc.string;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    auto B = N.iota.map!(i => tuple(i, A[i])).array;
    B.sort!"a[1] > b[1]";

    auto rbt = new RedBlackTree!int;
    long ans = 0;

    foreach (i; 0..N) {
        auto idx = B[i][0];
        auto a = B[i][1];
        auto lb1 = rbt.lowerBound(idx);
        auto ub1 = rbt.upperBound(idx);
        auto l1 = lb1.empty ? -1 : lb1.back;
        auto r1 = ub1.empty ? N : ub1.front;
        auto lb2 = rbt.lowerBound(l1);
        auto ub2 = rbt.upperBound(r1);
        auto l2 = lb2.empty ? -1 : lb2.back;
        auto r2 = ub2.empty ? N : ub2.front;

        if (lb1.empty && ub1.empty) {

        } else {
            ans += a * (r2 - r1) * (idx - l1);
            ans += a * (l1 - l2) * (r1 - idx);
        }

        rbt.insert(idx);
    }

    ans.writeln;
}