N=gets.to_i
ps=[nil]+gets.split.map(&:to_i)
ps_i=[]*(N+1)
ps.each_with_index do |o,i|
    next if i==0
    ps_i[o]=i
end
cd=[0,ps_i[N],N+1]
ans=0
(1..N-1).to_a.reverse.each do |e|
    ndx=cd.bsearch_index{|x|ps_i[e]<x}
    cd.insert(ndx,ps_i[e])
    if cd[ndx+1]==N+1
        r=0
    else
        r=e*(cd[ndx+2]-cd[ndx+1])*(cd[ndx]-cd[ndx-1])
    end
    if cd[ndx-1]==0
        l=0
    else
        l=e*(cd[ndx-1]-cd[ndx-2])*(cd[ndx+1]-cd[ndx])
    end
    ans+=r+l
end
p ans
