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

#!/usr/bin/env ruby

$log={}

def c140e(p, vec=:first, indent='')
  if p.size < 2
    return 0
  end

  # get the index of max, 2nd-max
  max = []
  if p[0] < p[1]
    max = [1, 0]
  else
    max = [0, 1]
  end
  (2...p.size).each do |index|
    if p[max[0]] < p[index]
      max = [index, max[0]]
    elsif p[max[1]] < p[index]
      max = [max[0], index]
    end
  end

  # call the left side, mid, right side
  second = p[max[1]]

  unless max[0] < max[1]
    max = [max[1], max[0]]
  end

  left = c140e(p[0...max[1]], :left, (vec!=:right) ? indent+'  ' : indent+'| ')

  if $log[p]
    mid = 0
#    $stderr.puts "#{indent}+- p=#{p} max=#{max} num=(dup)"
  else
    mid = second * (1 + max[0]) * (p.size - max[1])
    $log[p] = mid
#    $stderr.puts "#{indent}+- p=#{p} max=#{max} num=#{mid}"
  end

  right = c140e(p[max[0]+1...p.size], :right, (vec!=:left) ? indent+'  ' : indent+'| ')
  return left + mid + right
end

ARGF.gets
p = ARGF.gets.split.map(&:to_i)
puts c140e(p)