Problem:
Score: 500 points

Problem Statement

Given is a permutation P of \{1, 2, \ldots, N\}.

For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.

Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Constraints

2 \le N \le 10^5

1 \le P_i \le N

P_i \neq P_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \ldots P_N

Output

Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Sample Input 1

3
2 3 1

Sample Output 1

5

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

30

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

136

Solution in C++14 (GCC 5.4.1) (judge verdict: Accepted)

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<functional>
#include<assert.h>
#include<numeric>
using namespace std;
#define REP(i,m,n) for(int i=(int)(m) ; i < (int) (n) ; ++i )
#define rep(i,n) REP(i,0,n)
using ll = long long;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;
const ll mod=1e9+7 ;
using namespace std;


ll n;
ll a[100010];
ll l[100010];

ll flr(ll x){
    return max((ll)0,min((ll)(n+1),x));
}

int main(void){
    cin>>n;
    rep(i,n){
        cin>>a[i+1];
        l[a[i+1]]=i+1;
    }

    set<ll> s;
    s.insert(n+2);
    s.insert(n+1);
    s.insert(-1);
    s.insert(-2);
    
    s.insert(l[n]);
    ll c,w,x,y,z;
    long long ans=0;
    rep(i,n-1){
        ll ii=n-1-i;
        ll j=l[ii];
        s.insert(j);
        auto it=s.find(j);
        it--;
        it--;
        w=flr(*it);
        it++;
        x=flr(*it);
        it++;
        c=flr(*it);
        it++;
        y=flr(*it);
        it++;
        z=flr(*it);
        
        ans+=ii*((x-w)*(y-c)+(c-x)*(z-y));
    }
    cout<<ans;
}