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.15.1) (judge verdict: Runtime Error)

#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };

    ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        #[cfg(debug_assertions)]
        writeln!(&mut std::io::stderr(), concat!("[DEBUG] ", $(stringify!($a), "={:?} "),*), $($a),*);
    }
}

#[allow(unused_imports)]
use std::cmp::{min, max};
#[allow(unused_imports)]
use std::io::{stdout, stdin, BufWriter, Write};

fn solve(n:usize, k:usize, s: &Vec<char>) -> usize {
    let mut ans1 = 0;
    let mut seq = 0;
    let mut ranges = vec![];
    for i in 0..n {
        if s[i] == 'L' {
            if seq > 0 {
                ranges.push(seq);
            }
            seq = 0;
            if i > 0 {
                if s[i-1] == 'L' {
                    ans1 += 1;
                }
            }
        } else {
            seq += 1;
        }
    }
    if seq > 0 {
        ranges.push(seq-1);
    }
    ranges.sort();
    ranges.reverse();

    for i in 0..min(k, ranges.len()) {
        ans1 += ranges[i]+1;
    }
    min(ans1, n-1)
}

fn solve2(n:usize, k:usize, s: &Vec<char>) -> usize {
    let mut ans1 = 0;
    let mut seq = 0;
    let mut ranges = vec![];
    for i in (0..n).rev() {
        if s[i] == 'R' {
            if seq > 0 {
                ranges.push(seq);
            }
            seq = 0;
            if i < n-1 {
                if s[i+1] == 'R' {
                    ans1 += 1;
                }
            }
        } else {
            seq += 1;
        }
    }
    if seq > 0 {
        ranges.push(seq-1);
    }
    ranges.sort();
    ranges.reverse();
    for i in 0..min(k, ranges.len()) {
        ans1 += ranges[i]+1;
    }
    min(ans1, n-1)
}

fn main() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (write!(out,$($format)*).unwrap());
    }

    input!{
      n: usize,
      k: usize,
      mut s: chars,
    }

    let ans1 = solve(n, k, &s);
    let ans2 = solve2(n, k, &s);
    let ans = max(ans1, ans2);
    puts!("{}\n", ans);
}