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: Time Limit Exceeded)

package main

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

type MyScanner struct {
	sc *bufio.Scanner
}

type MyWriter struct {
	stdout io.Writer
}

type MyPut interface{}

func getScanner(fp io.Reader) *bufio.Scanner {
	sc := bufio.NewScanner(fp)
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 500001), 500000)
	return sc
}

func getHugeScanner(fp io.Reader, size int) *bufio.Scanner {
	sc := bufio.NewScanner(fp)
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, size), size)
	return sc
}

func (mysc *MyScanner)String() string {
	mysc.sc.Scan()
	return mysc.sc.Text()
}

func (mysc *MyScanner)Int() int {
	i, _ := strconv.Atoi(mysc.String())
	return i
}

func (mysc *MyScanner)Int64() int64 {
	i, _ := strconv.ParseInt(mysc.String(), 10, 64)
	return i
}

func (mysc *MyScanner)Float64() float64 {
	i, _ := strconv.ParseFloat(mysc.String(), 64)
	return i
}

func (mw MyWriter)Puts(v MyPut) {
	_, _ = fmt.Fprintf(mw.stdout, "%v\n", v)
}

func UpperBound(l []int, n int) (int, int) {
	k := sort.Search(len(l), func(i int) bool { return l[i] > n })
	if k == len(l) {
		return k, -1
	}
	return k, l[k]
}

func Solve(stdin io.Reader, stdout io.Writer) {
	sc := MyScanner{getScanner(stdin)}
	mw := MyWriter{stdout}

	n := sc.Int()

	p := make([]int, n + 1)
	idx := make([]int, n + 1)

	var up []int

	for i := 1; i <= n; i++ {
		v := sc.Int()
		p[i] = v
		idx[v] = i
	}

	ans := 0

	for v := n; v >= 1; v-- {
		i := idx[v]
		k, _ := UpperBound(up, i)
		if k < len(up) {
			up = append(up[:k + 1], up[k:]...)
			up[k] = i
		} else {
			up = append(up, i)
		}
		var ll, lr, rl, rr int
		k--
		if k < 0 {
			lr = 0
		} else {
			lr = up[k]
		}
		k--
		if k < 0 {
			ll = 0
		} else {
			ll = up[k]
		}
		k += 3
		if k < len(up) {
			rl = up[k]
		} else {
			rl = n + 1
		}
		k++
		if k < len(up) {
			rr = up[k]
		} else {
			rr = n + 1
		}
		ans += ((lr - ll) * (rl - i) + (i - lr) * (rr - rl)) * v
	}
	mw.Puts(ans)
}

func main() {
	Solve(os.Stdin, os.Stdout)
	return
}