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 PHP7 (7.0.15) (judge verdict: Time Limit Exceeded)

<?php

fscanf(STDIN, "%d", $n);

$array = explode(" ", trim(fgets(STDIN)));
$ans = 0;
$max = 0;
$max_pos = -1;
$second = 0;
$sec_pos = -1;
for($i=0;$i<$n;$i++){
    if($array[$i] == $n){
        $max = max($max, $array[$i]);
        if($max == $array[$i]){
            $max_pos = $i;
        }
        continue;
    }
    $k = $i -1;
    $b_1 = 0;
    $b_2 = 0;
    $a_1 = 0;
    $a_2 = 0;
    $t = 0;
    if($array[$i] > $max){
        $b_1 = $i + 1;
//    }elseif($array[$i] > $sec_pos){
  //      $b_1 = $i - $max_pos;
    //    $b_2 = $max_pos + 1;
    }else {
        while ($k >= 0) {
            if ($array[$k] > $array[$i]) {
                if ($t == 0) {
                    $b_1 = $i - $k;
                    $t = 1;
                } else {
                    $b_2 = $i - $b_1 - $k;
                    $t = 2;
                    break;
                }
            }
            $k--;
        }
        if ($t == 0) {
            $b_1 = $i + 1;
        } elseif ($t == 1) {
            $b_2 = $i - $b_1 + 1;
        }
    }
    $k = $i+1;
    $t = 0;
    while($k < $n){
        if($array[$k] > $array[$i]){
            if($t == 0){
                $a_1 = $k - $i;
                $t = 1;
            }else{
                $a_2 =  $k - $a_1 - $i;
                $t = 2;
                break;
            }
        }
        $k++;
    }
    if($t == 0){
        $a_1 = $n - $i;
    }elseif($t == 1){
        $a_2 = $n - $a_1 - $i;
    }
    $ans += (($b_2) * $a_1 + ($a_2) * $b_1) * $array[$i];
    $max = max($max, $array[$i]);
    if($max == $array[$i]){
        $max_pos = $i;
    }
}
echo $ans;