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 Go (1.6) (judge verdict: Accepted)

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

var sc, wr = bufio.NewScanner(os.Stdin), bufio.NewWriter(os.Stdout)

func scanString() string   { sc.Scan(); return sc.Text() }
func scanRunes() []rune    { return []rune(scanString()) }
func scanInt() int         { a, _ := strconv.Atoi(scanString()); return a }
func scanInt64() int64     { a, _ := strconv.ParseInt(scanString(), 10, 64); return a }
func scanFloat64() float64 { a, _ := strconv.ParseFloat(scanString(), 64); return a }

func scanInts(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = scanInt()
	}
	return res
}

func debug(a ...interface{}) { fmt.Fprintln(os.Stderr, a...) }

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

//•*¨*•.¸¸♪main•*¨*•.¸¸♪(　-ω-)ノ　(　・ω・)
func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 10000), 1001001)

	n := scanInt()
	ps := scanInts(n)

	bit := make(BIT, n+2)
	idx := make([]int, n+1)
	for i := 0; i < n; i++ {
		idx[ps[i]] = i+1
	}

	ans := 0
	for i := 0; i < n; i++ {
		num := n-i
		base := bit.Sum(idx[num])
		r1 := sort.Search(n+1-idx[num], func(idr int) bool {
			return 1 <= bit.Sum(idx[num]+idr)-base
		})+idx[num]
		r2 := sort.Search(n+1-idx[num], func(idr int) bool {
			return 2 <= bit.Sum(idx[num]+idr)-base
		})+idx[num]

		l1 := sort.Search(idx[num], func(idl int) bool {
			return -1 < bit.Sum(idl)-base
		})
		l2 := sort.Search(idx[num], func(idl int) bool {
			return -2 < bit.Sum(idl)-base
		})

		bit.Add(idx[num], 1)

		ans += ((r1-idx[num])*(l1-l2)+(r2-r1)*(idx[num]-l1))*(num)
		// debug(num,ans)
		// debug(idx[num], l2, l1, r1, r2)
	}

	fmt.Fprintln(wr, ans)

}

// BIT type
type BIT []int

// Sum function calculates a sum to i
func (t BIT) Sum(i int) int {
	s := 0
	for i++; i > 0; i -= i & -i {
		s += t[i]
	}
	return s
}

// Add function add x to i
func (t BIT) Add(i, x int) {
	for i++; i < len(t); i += i & -i {
		t[i] += x
	}
}