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 Rust (1.42.0) (judge verdict: Accepted)

use std::collections::BTreeSet;
use std::io::*;
use std::ops::Bound::Excluded;
use std::ops::Bound::Included;
use std::str::FromStr;

#[allow(dead_code)]
fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let n = read::<usize>();
    let mut ps = vec![(0, 0); n];
    for i in 0..n {
        ps[i].0 = read::<usize>();
        ps[i].1 = i;
    }
    ps.sort();
    ps.reverse();
    let mut items = BTreeSet::<i64>::new();
    let mut ans = 0;
    for i in 0..n {
        let v = ps[i].0 as i64;
        let pos = ps[i].1 as i64;
        let mut lefts = vec![];
        let mut rights = vec![];
        for index in items.range((Included(&0), Excluded(&(pos as i64)))).rev() {
            lefts.push(*index);
            if lefts.len() == 2 {
                break;
            }
        }
        for index in items.range((Excluded(&(pos as i64)), Included(&(n as i64)))) {
            rights.push(*index);
            if rights.len() == 2 {
                break;
            }
        }
        while lefts.len() <= 1 {
            lefts.push(-1);
        }
        while rights.len() <= 1 {
            rights.push(n as i64);
        }
        ans += v * (pos - lefts[0]) * (rights[1] - rights[0]);
        ans += v * (lefts[0] - lefts[1]) * (rights[0] - pos);
        items.insert(pos as i64);
    }
    println!("{}", ans);
}