N = gets.chomp.to_i
p = Array.new(N+1)
str = gets.split
for i in 0...N do
    a = str[i].to_i
    p[a] = i+1
end

q = Array.new(3,N+1)
q[0] = 0
q[1] = p[N]
answer = 0

for i in 2..N do
    a = p[-i]
    l = 1
    r = i
    while l != r
        c = (l+r)/2
        if a < q[c]
            r = c
        else
            l = c+1
        end
    end
    q.insert(l,a)

    b = N-i+1
    if q[l-1] == 0
        answer += b*(q[l]-q[l-1])*(q[l+2]-q[l+1])
    elsif q[l+1] > N
        answer += b*(q[l-1]-q[l-2])*(q[l+1]-q[l])
    else
        answer += b*((q[l-1]-q[l-2])*(q[l+1]-q[l])+(q[l]-q[l-1])*(q[l+2]-q[l+1]))
    end
end
puts answer