var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}
var BIT = (function(){
  function f(n){return new BIT(n);}
  function BIT(n){
    this.a = Array(n+1).fill(0);
  }
  BIT.prototype.add = function(x,i){
    for(;i<this.a.length;i+=i&-i)this.a[i]+=x;
  };
  BIT.prototype.get = function(i){
    for(var r=0;i;i-=i&-i)r+=this.a[i];
    return r;
  };
  return f;
})();

var n,p,bit,a;
console.log(main());
function main(){
  n = o.a();
  p = o.l();
  var ans = 0;
  bit = BIT(n+2);
  bit.add(2,1);
  bit.add(2,n+2);
  a = xArray(0,n);
  for(var i = 0; i < n; i++){
    a[p[i]-1] = i;
  }
  bit.add(1,a[n-1]+2);
  for(i = n-1; i--;){
    var x = bit.get(a[i]+2);
    var l1 = solve(0,a[i]+2,x);
    var l0 = solve(0,l1,x-1);
    var r1 = solve(a[i]+2,n+2,x+1);
    var r0 = solve(r1-1,n+2,x+2);
    ans += (l1-l0) * (r1-a[i]-2) * (i+1);
    ans += (r0-r1) * (a[i]+2-l1) * (i+1);
    bit.add(1,a[i]+2);
  }
  return ans;
}

function solve(ng,ok,x){
  while(ok-ng > 1){
    var m = ok+ng>>1;
    if(bit.get(m) >= x)ok = m;
    else ng = m;
  }
  return ok;
}