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: Wrong Answer)

#include<iostream>
#include<stack>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<algorithm>
#include<iomanip>
#include<set>
#include<bitset>
#include<cmath>
#include<numeric>
#include<limits>

#define REP(i, m, n) for(int i = (m); i < (n); i++)
#define rep(i,n) REP(i,0,n)
#define NIL -1
using namespace std;
typedef long long ll;
typedef long long int lli;
static const int MOD = 10000007;
static const int MAX = 100005;


int N;
typedef struct orderp {
  int key;
  int value;

  bool operator < ( const orderp& right ) const {
    return value > right.value;
  }
} ord;


void printset(multiset<ord> st) {
  cout << st.size() << ":";
  for (multiset<ord>::iterator it = st.begin(); it != st.end(); it++) {
    cout << " " << (*it).key;
  }
  cout << " \n";
}
void printsetint(multiset<int> st) {
  cout << st.size() << ":";
  for (multiset<int>::iterator it = st.begin(); it != st.end(); it++) {
    cout << " " << (*it);
  }
  cout << " \n";
}


int main(){
  cin >> N;
  int P[N+1];
  multiset<ord> kt;
  multiset<int> st;

  st.insert(-1);
  st.insert(-1);
  st.insert(N);
  st.insert(N);
  rep(i, N) {
    int p;
    cin >> p;
    kt.insert({i,p});
    P[i] = p;
  }
  // printset(kt);
  lli ans = 0;
  for ( auto k : kt) {
    auto itr = st.lower_bound(k.key);
    // itr++;
    auto idx1 = *itr;
    itr++;
    auto idx2 = *itr;
    itr--;
    itr--;
    auto idx3 = *itr;
    itr--;
    auto idx4 = *itr;
    // cout << k.key << " idx: " << idx1 << " " << idx2 << " " << idx3 << " " << idx4 << endl;
    ans += P[k.key]*(idx2 - idx1)*(k.key - idx3);
    ans += P[k.key]*(idx1 - k.key)*(idx3 - idx4);
    st.insert(k.key);
    // printsetint(st);
  }
  cout << ans << endl;

}