import java.util.*

fun simple(P: List<Long>): Long {
    var res = 0L
    for (i in P.indices) {
        for (k in 2..P.size - i) {
            val l = P.subList(i, i + k).sorted()
            res += l[l.size - 2]
        }
    }
    return res
}

fun main(args: Array<String>) {
    val N = readLine()!!.toInt()
    val P = readLine()!!.split(" ").map{it.toLong()}
    val Q = Array(N + 1) {0}

    for (i in P.indices) {
        Q[P[i].toInt()] = i
    }

    val st = TreeSet<Long>()
    var res = 0L

    for (k in N downTo 1) {
        val idx = Q[k].toLong()

        val l = st.lower(idx)
        val ll = idx - (l ?: -1L)
        val l2 = if (l == null) null else st.lower(l)
        val l2l = idx - (l2 ?: -1L)
        val r = st.higher(idx)
        val rl = (r ?: N.toLong()) - idx
        val r2 = if (r == null) null else st.higher(r)
        val r2l = (r2 ?: N.toLong()) - idx

        res += (l2l - ll) * rl * k
        res += ll * (r2l - rl) * k

        st.add(idx)
    }

    println(res)
//    println(simple(P))
}
