#d11002. 第二大数字和

第二大数字和

Sum of Second Largests

Problem Description

You are given a permutation PP of 1,2,…,N1, 2, \dots, N.

For a pair of indices {L,R}\{L, R\} (1≤L<R≤N1 \le L < R \le N), let XL,RX_{L,R} be the second largest value among PL,PL+1,…,PRP_L, P_{L+1}, \dots, P_R.

Compute the following sum:

∑L=1N−1∑R=L+1NXL,R\sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}

Input Format

The first line contains an integer NN.

The second line contains NN integers P1,P2,…,PNP_1, P_2, \dots, P_N.

Output Format

Output one line containing a single integer: the value of ∑L=1N−1∑R=L+1NXL,R\sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Sample Input

5
1 2 3 4 5

Sample Output

30

Constraints

2≤N≤1000002 \le N \le 100000, 1≤Pi≤N1 \le P_i \le N, and Pi≠PjP_i \neq P_j for i≠ji \neq j.

Hint

If you passed this problem in O(nlog⁡n)O(n \log n), try to think of a faster solution.