import std.stdio, std.string, std.conv;
import std.range, std.algorithm, std.array, std.typecons, std.container;
import std.math, std.numeric, core.bitop;

enum inf = 1_001_001_001;
enum inf6 = 1_001_001_001_001_001_001L;
enum mod = 1_000_000_007L;


void main() {
    int N;
    scan(N);
    auto P = readln.split.map!(x => x.to!int).enumerate.array;

    P.sort!"a.value > b.value"();
    debug {
        writeln(P);
    }

    auto rbt = redBlackTree(-1, N);
    long ans;

    foreach (pi; P) {
        auto i = pi.index.to!int;
        auto v = pi.value;

        int L1, L2, R1, R2;
        L1 = L2 = R1 = R2 = i;
        auto lw = rbt.lowerBound(i);
        auto up = rbt.upperBound(i);
        L1 = L2 = lw.back;
        if (L1 != -1) {
            lw.popBack();
            L2 = lw.back;
        }
        R1 = R2 = up.front;
        if (R1 != N) {
            up.popFront();
            R2 = up.front;
        }
        ans += 1L * (i - L1) * (R2 - R1) * v;
        ans += 1L * (L1 - L2) * (R1 - i) * v;

        rbt.insert(i);
    }

    writeln(ans);
}







void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

bool chmin(T, U...)(ref T x, U args) {
    bool isChanged;

    foreach (arg; args) {
        if (x > arg) {
            x = arg;
            isChanged = true;
        }
    }

    return isChanged;
}

bool chmax(T, U...)(ref T x, U args) {
    bool isChanged;

    foreach (arg; args) {
        if (x < arg) {
            x = arg;
            isChanged = true;
        }
    }

    return isChanged;
}
