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-----
3
2 3 1

-----Sample Output-----
5

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

Difficulty: MEDIUM_HARD

Solutions:
N = int(input())
P = list(map(int, input().split()))
left_bigger = [0] + [i for i in range(N + 1)]
right_bigger = [i + 1 for i in range(N + 1)] + [N + 1]
E = [(v, i + 1) for (i, v) in enumerate(P)]
E.sort()
ans = 0
for (v, i) in E:
	l0 = left_bigger[i]
	l1 = left_bigger[l0]
	r0 = right_bigger[i]
	r1 = right_bigger[r0]
	ans += ((r1 - r0) * (i - l0) + (r0 - i) * (l0 - l1)) * v
	left_bigger[r0] = l0
	right_bigger[l0] = r0
print(ans)


import sys
from heapq import heappush, heappop
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007

def main():
	(N, *P) = map(int, read().split())
	idx = [0] * (N + 1)
	for (i, p) in enumerate(P):
		idx[p] = i
	left = list(range(-1, N)) + [-1]
	right = list(range(1, N + 1)) + [N, N]
	ans = 0
	for n in range(1, N + 1):
		i = idx[n]
		l1 = left[i]
		l2 = left[l1]
		r1 = right[i]
		r2 = right[r1]
		ans += n * ((l1 - l2) * (r1 - i) + (r2 - r1) * (i - l1))
		left[r1] = l1
		right[l1] = r1
	print(ans)
	return
main()


import sys
input = sys.stdin.readline
n = int(input())
a = [int(j) for j in input().split()]
ans = 0
ind = [0] * (n + 1)
for i in range(n):
	ind[a[i]] = i + 1
l = [0] + list(range(n + 1))
r = list(range(1, n + 2)) + [n + 1]
for i in range(1, n + 1):
	l1 = l[ind[i]]
	l0 = l[l1]
	r0 = r[ind[i]]
	r1 = r[r0]
	ans += ((l1 - l0) * (r0 - ind[i]) + (r1 - r0) * (ind[i] - l1)) * i
	l[r0] = l1
	r[l1] = r0
print(ans)


N = int(input())
(*P,) = map(int, input().split())
LL = [0] + [i for i in range(N + 1)]
RR = [i + 1 for i in range(N + 1)] + [N + 1]
E = [(v, i + 1) for (i, v) in enumerate(P)]
E.sort()
ans = 0
for (v, i) in E:
	l0 = LL[i]
	l1 = LL[l0]
	r0 = RR[i]
	r1 = RR[r0]
	(LL[RR[i]], RR[LL[i]]) = (LL[i], RR[i])
	ans += ((r1 - r0) * (i - l0) + (r0 - i) * (l0 - l1)) * v
print(ans)


def solve():
	N = int(input())
	Ps = list(map(int, input().split()))

	def makeBIT(numEle):
		numPow2 = 2 ** (numEle - 1).bit_length()
		data = [0] * (numPow2 + 1)
		return (data, numPow2)

	def addValue(iA, A):
		iB = iA + 1
		while iB <= numPow2:
			data[iB] += A
			iB += iB & -iB

	def getSum(iA):
		iB = iA + 1
		ans = 0
		while iB > 0:
			ans += data[iB]
			iB -= iB & -iB
		return ans
	(data, numPow2) = makeBIT(N)
	iPs = list(range(N))
	iPs.sort(key=lambda iP: Ps[iP])
	ans = 0
	for iP in reversed(iPs):
		v = getSum(iP)
		Bs = []
		for x in range(v - 1, v + 3):
			if x <= 0:
				L = -1
			elif getSum(numPow2 - 1) < x:
				L = N
			else:
				maxD = numPow2.bit_length() - 1
				L = 0
				S = 0
				for d in reversed(range(maxD)):
					if S + data[L + (1 << d)] < x:
						S += data[L + (1 << d)]
						L += 1 << d
			Bs.append(L)
		num = (Bs[1] - Bs[0]) * (Bs[2] - iP) + (iP - Bs[1]) * (Bs[3] - Bs[2])
		ans += Ps[iP] * num
		addValue(iP, 1)
	print(ans)
solve()


from bisect import bisect_left, bisect_right, insort_right

class SquareSkipList:

	def __init__(self, values=None, sorted_=False, square=1000, seed=42):
		inf = float('inf')
		self.rand_y = seed
		self.square = square
		if values is None:
			self.layer1 = []
			self.layer0 = [[]]
		else:
			self.layer1 = layer1 = []
			self.layer0 = layer0 = []
			if not sorted_:
				values.sort()
			rand_depth = self.rand_depth
			l0 = []
			for v in values:
				if rand_depth():
					layer0.append(l0)
					l0 = []
					layer1.append(v)
				else:
					l0.append(v)
			layer0.append(l0)
		self.layer1.append(inf)

	def rand_depth(self):
		y = self.rand_y
		y ^= y << 13 & 4294967295
		y ^= y >> 17
		y ^= y << 5 & 4294967295
		self.rand_y = y
		return y % self.square == 0

	def add(self, x):
		(layer1, layer0) = (self.layer1, self.layer0)
		if self.rand_depth():
			idx1 = bisect_right(layer1, x)
			layer1.insert(idx1, x)
			layer0_idx1 = layer0[idx1]
			idx0 = bisect_right(layer0_idx1, x)
			layer0.insert(idx1 + 1, layer0_idx1[idx0:])
			del layer0_idx1[idx0:]
		else:
			idx1 = bisect_right(layer1, x)
			insort_right(layer0[idx1], x)

	def remove(self, x):
		(layer1, layer0) = (self.layer1, self.layer0)
		idx1 = bisect_left(layer1, x)
		if layer1[idx1] == x:
			del layer1[idx1]
			layer0[idx1] += layer0[idx1 + 1]
			del layer0[idx1 + 1]
		else:
			layer0_idx1 = layer0[idx1]
			del layer0_idx1[bisect_left(layer0_idx1, x)]

	def bisect_left(self, x):
		(layer1, layer0) = (self.layer1, self.layer0)
		idx1 = bisect_left(layer1, x)
		res = layer1[idx1]
		if res == x:
			return res
		layer0_idx1 = layer0[idx1]
		if layer0_idx1:
			idx0 = bisect_left(layer0_idx1, x)
			if idx0 == len(layer0_idx1):
				return res
			else:
				return layer0_idx1[idx0]
		else:
			return res

	def search_higher(self, x):
		(layer1, layer0) = (self.layer1, self.layer0)
		idx1 = bisect_right(layer1, x)
		layer0_idx1 = layer0[idx1]
		idx0 = bisect_right(layer0_idx1, x)
		if idx0 == len(layer0_idx1):
			return layer1[idx1]
		return layer0_idx1[idx0]

	def search_lower(self, x):
		(layer1, layer0) = (self.layer1, self.layer0)
		idx1 = bisect_left(layer1, x)
		layer0_idx1 = layer0[idx1]
		idx0 = bisect_left(layer0_idx1, x)
		if idx0 == 0:
			return layer1[idx1 - 1]
		return layer0_idx1[idx0 - 1]

	def pop(self, idx):
		(layer1, layer0) = (self.layer1, self.layer0)
		s = -1
		for (i, l0) in enumerate(layer0):
			s += len(l0) + 1
			if s >= idx:
				break
		if s == idx:
			layer0[i] += layer0[i + 1]
			del layer0[i + 1]
			return layer1.pop(i)
		else:
			return layer0[i].pop(idx - s)

	def print(self):
		print(self.layer1)
		print(self.layer0)

def main():
	n = int(input())
	p = list(map(int, input().split()))
	idx = [0] * n
	for i in range(0, n):
		idx[i] = i
	idx.sort(key=lambda i: -p[i])
	ssl = SquareSkipList()
	ssl.add(-1)
	ssl.add(n)
	ans = 0
	for i in idx:
		nex = ssl.search_higher(i)
		nexnex = ssl.search_higher(nex)
		pre = ssl.search_lower(i)
		prepre = ssl.search_lower(pre)
		if prepre != float('inf'):
			ans += p[i] * (pre - prepre) * (nex - i)
		if nexnex != float('inf'):
			ans += p[i] * (i - pre) * (nexnex - nex)
		ssl.add(i)
	print(ans)
main()


n = int(input())
p = list(map(int, input().split()))
l = [0] + [i for i in range(n + 1)]
r = [i + 1 for i in range(n + 1)] + [n + 1]
d = [0] * (n + 1)
for i in range(n):
	d[p[i]] = i + 1
ans = 0
for i in range(1, n + 1):
	ans += ((r[r[d[i]]] - r[d[i]]) * (d[i] - l[d[i]]) + (r[d[i]] - d[i]) * (l[d[i]] - l[l[d[i]]])) * i
	(l[r[d[i]]], r[l[d[i]]]) = (l[d[i]], r[d[i]])
print(ans)


import bisect

class SqrtSet:

	def __init__(self, block_limit=201):
		self.key = []
		self.child = [[]]
		self.block_limit = block_limit

	def search_lower(self, key):
		if key is None:
			return None
		ret = None
		i = bisect.bisect_left(self.key, key)
		if i != 0:
			ret = self.key[i - 1]
		block = self.child[i]
		i = bisect.bisect_left(block, key)
		if i != 0:
			ret = block[i - 1]
		return ret

	def search_higher(self, key):
		if key is None:
			return None
		ret = None
		i = bisect.bisect_right(self.key, key)
		if i != len(self.key):
			ret = self.key[i]
		block = self.child[i]
		i = bisect.bisect_right(block, key)
		if i != len(block):
			ret = block[i]
		return ret

	def insert(self, key):
		i = bisect.bisect(self.key, key)
		block = self.child[i]
		bisect.insort(block, key)
		if len(block) == self.block_limit:
			sep = self.block_limit // 2
			self.key.insert(i, block[sep])
			self.child.insert(i + 1, block[sep + 1:])
			self.child[i] = block[:sep]

	def dump(self):
		for b in self.child:
			print(len(b), end=' ')
		print('')

def main():
	n = int(input())
	p = list(map(int, input().split()))
	idx = [0] * n
	for i in range(0, n):
		idx[i] = i
	idx.sort(key=lambda i: -p[i])
	t = SqrtSet()
	t.insert(-10)
	t.insert(n + 10)
	ans = 0
	for i in range(n):
		if i == 0:
			t.insert(idx[i])
			continue
		ri = t.search_higher(idx[i])
		pri = t.search_higher(ri)
		if pri == None:
			pri = n
			ri = n
		if pri == n + 10:
			pri = n
		le = t.search_lower(idx[i])
		ple = t.search_lower(le)
		if ple == None:
			if le == -10:
				le = -1
				ple = -1
		if ple == -10:
			ple = -1
		ans += (n - i) * ((le - ple) * (ri - idx[i]) + (pri - ri) * (idx[i] - le))
		t.insert(idx[i])
	print(ans)
main()


def argsort(a):
	return list(map(lambda z: z[1], sorted(zip(a, range(len(a))))))
N = int(input())
P = list(map(int, input().split()))
a = argsort(P)
left = [i for i in range(N)]
right = [i for i in range(N)]
result = 0
for i in range(1, N):
	k = a[i - 1]
	extend_left = k - 1 >= 0 and P[k - 1] < i
	extend_right = k + 1 < N and P[k + 1] < i
	if extend_left and extend_right:
		L = left[k - 1]
		R = right[k + 1]
	elif extend_left:
		L = left[k - 1]
		R = k
	elif extend_right:
		R = right[k + 1]
		L = k
	else:
		L = k
		R = k
	right[L] = R
	left[R] = L
	if L - 1 >= 0:
		if L - 2 >= 0 and P[L - 2] < i:
			LL = left[L - 2]
		else:
			LL = L - 1
		result += (L - 1 - LL + 1) * (R - k + 1) * i
	if R + 1 < N:
		if R + 2 < N and P[R + 2] < i:
			RR = right[R + 2]
		else:
			RR = R + 1
		result += (RR - (R + 1) + 1) * (k - L + 1) * i
print(result)


import sys
sys.setrecursionlimit(2147483647)
INF = float('inf')
MOD = 10 ** 9 + 7
input = lambda : sys.stdin.readline().rstrip()

class BIT(object):

	def __init__(self, A, dot, e, inv=None):
		n = len(A)
		self.__n = n
		self.__dot = dot
		self.__e = e
		self.__inv = inv
		self.__node = ['$'] + A
		for i in range(1, n + 1):
			j = i + (i & -i)
			if j <= n:
				self.__node[j] = dot(self.__node[i], self.__node[j])

	def add(self, i, w=1):
		i += 1
		while i <= self.__n:
			self.__node[i] = self.__dot(self.__node[i], w)
			i += i & -i

	def sum(self, i):
		res = self.__e
		while i > 0:
			res = self.__dot(res, self.__node[i])
			i -= i & -i
		return res

	def range_sum(self, l, r):
		assert self.__inv
		return self.__inv(self.sum(r), self.sum(l))

	def bisect_left(self, w, increase=True):
		n = self.__n
		k = 2 ** (self.__n - 1).bit_length()
		res = 0
		now = self.__e
		while k:
			if res + k <= n and self.__dot(now, self.__node[res + k]) < w and increase:
				now = self.__dot(now, self.__node[res + k])
				res += k
			elif res + k <= n and self.__dot(now, self.__node[res + k]) > w and (not increase):
				now = self.__dot(now, self.__node[res + k])
				res += k
			k //= 2
		return res

def resolve():
	n = int(input())
	A = list(map(int, input().split()))
	idx = [0] * n
	for (i, a) in enumerate(A):
		idx[a - 1] = i
	from operator import add
	bit = BIT([0] * n, add, 0)
	ans = 0
	for k in range(n, 0, -1):
		i = idx[k - 1]
		bit.add(i)
		s = bit.sum(i + 1)
		l0 = bit.bisect_left(s - 1) - (s <= 1)
		l1 = bit.bisect_left(s - 2) - (s <= 2)
		r0 = bit.bisect_left(s + 1)
		r1 = bit.bisect_left(s + 2)
		ans += k * ((i - l0) * (r1 - r0) + (l0 - l1) * (r0 - i))
	print(ans)
resolve()


N = int(input())
P = [None] + [int(x) for x in input().split()]
id_list = [None] * (N + 1)
for (i, x) in enumerate(P[1:], 1):
	id_list[x] = i

class BIT:

	def __init__(self, n):
		self.size = n
		self.tree = [0] * (n + 1)

	def add(self, i, x=1):
		while i <= self.size:
			self.tree[i] += x
			i += i & -i

	def sum(self, i):
		s = 0
		while i > 0:
			s += self.tree[i]
			i -= i & -i
		return s

	def search(self, x):
		i = 0
		s = 0
		step = 1 << N.bit_length() - 1
		while step:
			if i + step <= N and s + self.tree[i + step] < x:
				i += step
				s += self.tree[i]
			step >>= 1
		return i + 1

def main():
	bit = BIT(N)
	ans = 0
	for x in range(N, 0, -1):
		idx = id_list[x]
		L = bit.sum(idx)
		bit.add(idx)
		R = N - x - L
		ll = bit.search(L - 1) if L >= 2 else 0
		l = bit.search(L) if L >= 1 else 0
		r = bit.search(L + 2) if R >= 1 else N + 1
		rr = bit.search(L + 3) if R >= 2 else N + 1
		coef = 0
		if l != 0:
			coef += (l - ll) * (r - idx)
		if r != 0:
			coef += (rr - r) * (idx - l)
		ans += x * coef
	print(ans)
main()


import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10 ** 9))
write = lambda x: sys.stdout.write(x + '\n')
n = int(input())
p = list(map(lambda x: int(x) - 1, input().split()))

def init(bit, values):
	for (i, v) in enumerate(values):
		add(bit, i + 1, v)

def query(bit, i):
	res = 0
	while i > 0:
		res += bit[i]
		i -= i & -i
	return res

def add(bit, i, x):
	if i == 0:
		raise RuntimeError
	while i <= len(bit) - 1:
		bit[i] += x
		i += i & -i
	return

def index(bit, v):
	i = 0
	n = len(bit) - 1
	k = 1 << (n - 1).bit_length()
	while k > 0:
		if i + k < n + 1 and bit[i + k] < v:
			v -= bit[i + k]
			i += k
		k //= 2
	if v == 1:
		return i + 1
	else:
		return n + 1
ind = [None] * n
for (i, num) in enumerate(p):
	ind[num] = i
bit = [0] * (n + 1)
l = [None] * n
l2 = [None] * n
r = [None] * n
r2 = [None] * n
for num in range(n - 1, -1, -1):
	i = query(bit, ind[num])
	if i == 0:
		l[ind[num]] = -1
		l2[ind[num]] = -1
	elif i == 1:
		l[ind[num]] = index(bit, i) - 1
		l2[ind[num]] = -1
	else:
		l[ind[num]] = index(bit, i) - 1
		l2[ind[num]] = index(bit, i - 1) - 1
	r[ind[num]] = index(bit, i + 1) - 1
	r2[ind[num]] = index(bit, i + 2) - 1
	add(bit, ind[num] + 1, 1)
ans = 0
for (i, (num, li, li2, ri, ri2)) in enumerate(zip(p, l, l2, r, r2)):
	v = 0
	if li >= 0:
		v += (ri - i) * (li - li2)
	if ri < n:
		v += (i - li) * (ri2 - ri)
	ans += v * (num + 1)
print(ans)


def rotate(nd, d):
	c = nd[d]
	if d:
		e = c[1]
		nd[1] = c[0]
		c[0] = nd
	else:
		e = c[0]
		nd[0] = c[1]
		c[1] = nd
	r = c[4] = nd[4]
	nd[4] = r - (e[4] if e else 0) - 1
	return c
root = None

def insert(val, pri):
	global root
	st = []
	dr = []
	x = root
	while x:
		st.append(x)
		if x[2] == val:
			return
		d = x[2] < val
		dr.append(d)
		x = x[d]
	nd = [None, None, val, pri, 1]
	while st:
		x = st.pop()
		d = dr.pop()
		x[d] = nd
		x[4] += 1
		if x[3] >= nd[3]:
			break
		rotate(x, d)
	else:
		root = nd
	for x in st:
		x[4] += 1

def __delete(nd):
	st = []
	dr = []
	while nd[0] or nd[1]:
		l = nd[0]
		r = nd[1]
		d = l[3] <= r[3] if l and r else l is None
		st.append(rotate(nd, d))
		dr.append(d ^ 1)
	nd = x = None
	while st:
		nd = x
		x = st.pop()
		d = dr.pop()
		x[d] = nd
		x[4] -= 1
	return x

def delete(val):
	global root
	x = root
	st = []
	y = None
	while x:
		if val == x[2]:
			break
		y = x
		d = x[2] < val
		st.append(y)
		x = x[d]
	else:
		return
	if y:
		y[d] = __delete(x)
		for x in st:
			x[4] -= 1
	else:
		root = __delete(x)

def find(val):
	global root
	x = root
	while x:
		if val == x[2]:
			return 1
		x = x[x[2] < val]
	return 0

def search1(val):
	global root
	x = root
	ans = -1
	while x:
		if val == x[2]:
			return val
		if val > x[2]:
			ans = max(ans, x[2])
			if x[1] == None:
				return ans
			else:
				x = x[1]
		if val < x[2]:
			if x[0] == None:
				return ans
			else:
				x = x[0]
	return ans

def search2(val):
	global root, N
	x = root
	ans = N
	while x:
		if val == x[2]:
			return val
		if val > x[2]:
			if x[1] == None:
				return ans
			else:
				x = x[1]
		if val < x[2]:
			ans = min(ans, x[2])
			if x[0] == None:
				return ans
			else:
				x = x[0]
	return ans
import random
N = int(input())
P = list(map(int, input().split()))
dic = {key: -1 for key in range(1, N + 1)}
for i in range(0, N):
	dic[P[i]] = i
answer = 0
for i in range(0, N):
	k = N - i
	l1 = search1(dic[k])
	l2 = search1(l1 - 1)
	r1 = search2(dic[k])
	r2 = search2(r1 + 1)
	answer += k * (dic[k] - l1) * (r2 - r1) + k * (l1 - l2) * (r1 - dic[k])
	insert(dic[k], random.randint(1, 100000))
print(answer)


N = int(input())
P_id = [0] * (N + 1)
for (index, p) in enumerate(map(int, input().split())):
	P_id[p] = index
left_next_index = list(range(-1, N - 1)) + ['うんこ', -1]
right_next_index = list(range(1, N + 1)) + [N, 'うんこ']
res = 0
for p in range(1, N):
	l1 = left_next_index[P_id[p]]
	l2 = left_next_index[l1]
	r1 = right_next_index[P_id[p]]
	r2 = right_next_index[r1]
	res += p * ((l1 - l2) * (r1 - P_id[p]) + (P_id[p] - l1) * (r2 - r1))
	left_next_index[r1] = l1
	right_next_index[l1] = r1
print(res)


import time
import random

class TreapNode:

	def __init__(self, key, pri):
		self.left = None
		self.right = None
		self.key = key
		self.pri = pri

class Treap:

	def __init__(self):
		self.root = None

	def search_lower(self, key):
		if key == None:
			return None
		ptr = self.root
		ret = None
		while ptr is not None:
			pk = ptr.key
			if pk < key:
				ret = pk
				ptr = ptr.right
			else:
				ptr = ptr.left
		return ret

	def search_higher(self, key):
		if key == None:
			return None
		ptr = self.root
		ret = None
		while ptr is not None:
			pk = ptr.key
			if pk > key:
				ret = pk
				ptr = ptr.left
			else:
				ptr = ptr.right
		return ret

	def insert(self, key):
		pri = random.randrange(0, 2 ** 25)
		ptr = self.root
		elem = TreapNode(key, pri)
		if ptr is None or ptr.pri < pri:
			self.root = elem
		else:
			while True:
				if key < ptr.key:
					left = ptr.left
					if left is None or left.pri < pri:
						ptr.left = elem
						ptr = left
						break
					ptr = left
				else:
					right = ptr.right
					if right is None or right.pri < pri:
						ptr.right = elem
						ptr = right
						break
					ptr = right
		left = elem
		right = elem
		while ptr is not None:
			if key < ptr.key:
				right.left = ptr
				right = ptr
				ptr = ptr.left
			else:
				left.right = ptr
				left = ptr
				ptr = ptr.right
		left.right = None
		right.left = None
		(elem.left, elem.right) = (elem.right, elem.left)

	def dump(self):
		self.__dump(self.root, 0)

	def __dump(self, idx, dep):
		if idx is not None:
			self.__dump(idx.right, dep + 1)
			for _ in range(0, dep):
				print('   ', end='')
			print([idx.key, idx.pri])
			self.__dump(idx.left, dep + 1)

def main():
	n = int(input())
	p = list(map(int, input().split()))
	idx = [0] * n
	for i in range(0, n):
		idx[i] = i
	idx.sort(key=lambda i: -p[i])
	t = Treap()
	t.insert(-1)
	t.insert(n)
	ans = 0
	for i in idx:
		nex = t.search_higher(i)
		nexnex = t.search_higher(nex)
		pre = t.search_lower(i)
		prepre = t.search_lower(pre)
		if prepre != None:
			ans += p[i] * (pre - prepre) * (nex - i)
		if nexnex != None:
			ans += p[i] * (i - pre) * (nexnex - nex)
		t.insert(i)
	print(ans)
main()


class BinaryIndexedTree:

	def __init__(self, size):
		size = 1 << (size - 1).bit_length()
		self.data = [0] * (size + 1)
		self.size = size

	def add(self, i, w):
		i += 1
		while i <= self.size:
			self.data[i] += w
			i += i & -i

	def sum(self, i):
		result = 0
		while i > 0:
			result += self.data[i]
			i -= i & -i
		return result
	__getitem__ = sum

	def lower_bound(self, v):
		(s, pos) = (0, 0)
		N = self.size
		k = N
		while k > 0:
			i = pos + k
			if i <= N:
				x = s + self.data[i]
				if x < v:
					s = x
					pos = i
			k >>= 1
		return pos

def naive(P):

	def it():
		for i in range(len(P) - 1):
			for j in range(i + 1, len(P)):
				yield sorted(P[i:j + 1])[-2]
	return sum(it())

def solve(P):

	def it():
		bit = BinaryIndexedTree(len(P))
		for (cnt, (v, i)) in enumerate(sorted(((v, i) for (i, v) in enumerate(P)), reverse=True)):
			bit.add(i, 1)
			c = bit.sum(i)
			low1 = -1 if c <= 0 else bit.lower_bound(c)
			low2 = -1 if c <= 1 else bit.lower_bound(c - 1)
			up1 = len(P) if c > cnt - 1 else bit.lower_bound(c + 2)
			up2 = len(P) if c > cnt - 2 else bit.lower_bound(c + 3)
			yield (v * ((up1 - i) * (low1 - low2) + (i - low1) * (up2 - up1)))
	return sum(it())
N = int(input())
P = list(map(int, input().split()))
print(solve(P))


N = int(input())
P = list(map(int, input().split()))
index_lst = [0] * N
for (index, i) in enumerate(P):
	index_lst[i - 1] = index
left_next_Index = list(range(-1, N - 1)) + [-1, -1]
right_next_Index = list(range(1, N + 1)) + [N, N]
ans = 0
for i in range(1, N):
	index = index_lst[i - 1]
	l1 = left_next_Index[index]
	l2 = left_next_Index[l1]
	r1 = right_next_Index[index]
	r2 = right_next_Index[r1]
	ans += i * ((index - l1) * (r2 - r1) + (r1 - index) * (l1 - l2))
	left_next_Index[r1] = l1
	right_next_Index[l1] = r1
print(ans)


import bisect
n = int(input())
p = list(map(int, input().split()))
idx = [0] * (n + 1)
for (i, p_i) in enumerate(p):
	idx[p_i] = i
right_idx = list(range(1, n + 1)) + [n, n]
left_idx = list(range(-1, n - 1)) + [-1, -1]
ans = 0
for p in range(1, n + 1):
	x = idx[p]
	r1 = right_idx[x]
	r2 = right_idx[r1]
	l1 = left_idx[x]
	l2 = left_idx[l1]
	ans += p * ((x - l1) * (r2 - r1) + (l1 - l2) * (r1 - x))
	right_idx[l1] = r1
	left_idx[r1] = l1
print(ans)


import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from operator import itemgetter
n = int(readline())
ppp = list(map(int, readline().split()))

def BIT_add(i, x):
	while i <= n:
		tree[i] += x
		i += i & -i

def BIT_sum(i):
	s = 0
	while i:
		s += tree[i]
		i -= i & -i
	return s

def BIT_search(x):
	i = 0
	s = 0
	step = 1 << n.bit_length() - 1
	while step:
		if i + step <= n and s + tree[i + step] < x:
			i += step
			s += tree[i]
		step >>= 1
	return i + 1
q = sorted(enumerate(ppp, 1), key=itemgetter(1), reverse=True)
tree = [0] * (n + 1)
ans = 0
for (i, p) in q:
	L = BIT_sum(i)
	BIT_add(i, 1)
	R = n - p - L
	LL = BIT_search(L - 1) if L >= 2 else 0
	LR = BIT_search(L) if L >= 1 else 0
	RL = BIT_search(L + 2) if R >= 1 else n + 1
	RR = BIT_search(L + 3) if R >= 2 else n + 1
	ans += p * ((LR - LL) * (RL - i) + (RR - RL) * (i - LR))
print(ans)


n = int(input())
p = list(map(int, input().split()))
id = [0] * (n + 1)
for (i, p_i) in enumerate(p):
	id[p_i] = i
r = list(range(1, n + 1)) + [n, n]
l = list(range(-1, n - 1)) + [-1, -1]
ans = 0
for p in range(1, n + 1):
	x = id[p]
	r1 = r[x]
	r2 = r[r1]
	l1 = l[x]
	l2 = l[l1]
	ans += p * ((x - l1) * (r2 - r1) + (l1 - l2) * (r1 - x))
	r[l1] = r1
	l[r1] = l1
print(ans)


class Node:

	def __init__(self, key=None):
		self.key = key
		self.balance = 'E'
		self.parent = None
		self.left = None
		self.right = None

class AVL:

	def __init__(self):
		self.root = Node()
		self.root.parent = Node('nil')

	def insert(self, key):
		if self.root.key is None:
			self.root.key = key
			return
		cursor = self.root
		while cursor:
			p = cursor
			if key == cursor.key:
				return
			elif key < cursor.key:
				cursor = cursor.left
			else:
				cursor = cursor.right
		new_node = Node(key)
		new_node.parent = p
		if key < p.key:
			p.left = new_node
		else:
			p.right = new_node
		return self.rebalance(p, new_node, key)

	def rebalance(self, u, v, key):
		while u.key != 'nil':
			if u.key > v.key:
				if u.balance == 'R':
					u.balance = 'E'
					return
				elif u.balance == 'L':
					if v.balance == 'L':
						self.rotate_R(u, v)
						return
					elif v.balance == 'R':
						self.rotate_LR(u, v)
						return
				else:
					u.balance = 'L'
					v = u
					u = u.parent
			elif u.balance == 'L':
				u.balance = 'E'
				return
			elif u.balance == 'R':
				if v.balance == 'R':
					self.rotate_L(u, v)
					return
				elif v.balance == 'L':
					self.rotate_RL(u, v)
					return
			else:
				u.balance = 'R'
				v = u
				u = u.parent

	def replace(self, u, v):
		if u.parent.left == u:
			u.parent.left = v
		else:
			u.parent.right = v
		v.parent = u.parent
		if v.parent.key == 'nil':
			self.root = v

	def rotate_R(self, u, v):
		w = v.right
		self.replace(u, v)
		v.right = u
		u.parent = v
		u.left = w
		if w:
			w.parent = u
		u.balance = 'E'
		v.balance = 'E'

	def rotate_L(self, u, v):
		w = v.left
		self.replace(u, v)
		v.left = u
		u.parent = v
		u.right = w
		if w:
			w.parent = u
		u.balance = 'E'
		v.balance = 'E'

	def rotate_LR(self, u, v):
		w = v.right
		self.replace(u, w)
		if w.left:
			v.right = w.left
			v.right.parent = v
		else:
			v.right = None
		if w.right:
			u.left = w.right
			u.left.parent = u
		else:
			u.left = None
		v.parent = w
		w.left = v
		u.parent = w
		w.right = u
		if w.balance == 'R':
			u.balance = 'E'
			v.balance = 'L'
		elif w.balance == 'L':
			u.balance = 'R'
			v.balance = 'E'
		else:
			u.balance = 'E'
			v.balance = 'E'
		w.balance = 'E'

	def rotate_RL(self, u, v):
		w = v.left
		self.replace(u, w)
		if w.left:
			w.left.parent = u
			u.right = w.left
		else:
			u.right = None
		if w.right:
			w.right.parent = v
			v.left = w.right
		else:
			v.left = None
		u.parent = w
		w.left = u
		v.parent = w
		w.right = v
		if w.balance == 'R':
			u.balance = 'L'
			v.balance = 'E'
		elif w.balance == 'L':
			u.balance = 'E'
			v.balance = 'R'
		else:
			u.balance = 'E'
			v.balance = 'E'
		w.balance = 'E'

	def find(self, key):
		cursor = self.root
		while cursor:
			if cursor.key == key:
				return cursor
			if key < cursor.key:
				cursor = cursor.left
			else:
				cursor = cursor.right
		return None

	def next_greater_key(self, cursor):
		if cursor is None:
			return
		if cursor.right:
			cursor = cursor.right
			while cursor.left:
				cursor = cursor.left
			return cursor
		elif cursor.parent.left == cursor:
			return cursor.parent
		elif cursor.parent.right == cursor:
			while cursor.parent.key != 'nil' and cursor.parent.right == cursor:
				cursor = cursor.parent
			if cursor.parent.key != 'nil':
				return cursor.parent
		else:
			return None

	def next_smaller_key(self, cursor):
		if cursor is None:
			return
		if cursor.left:
			cursor = cursor.left
			while cursor.right:
				cursor = cursor.right
			return cursor
		elif cursor.parent.right == cursor:
			return cursor.parent
		elif cursor.parent.left == cursor:
			while cursor.parent.key != 'nil' and cursor.parent.left == cursor:
				cursor = cursor.parent
			if cursor.parent.key != 'nil':
				return cursor.parent

	def get_smaller_key(self, key):
		cursor = self.find(key)
		l1 = self.next_smaller_key(cursor)
		l2 = self.next_smaller_key(l1)
		if l2 is None:
			l2 = 0
		else:
			l2 = l2.key
		return (l1.key, l2)

	def get_greater_key(self, key):
		cursor = self.find(key)
		r1 = self.next_greater_key(cursor)
		r2 = self.next_greater_key(r1)
		if r2 is None:
			r2 = 0
		else:
			r2 = r2.key
		return (r1.key, r2)

def main():
	import sys
	input = sys.stdin.readline
	N = int(input())
	P = map(int, input().split())
	idx = [-1] * (N + 1)
	for (i, v) in enumerate(P, 1):
		idx[v] = i
	avl = AVL()
	for i in [0, idx[N], N + 1]:
		avl.insert(i)
	total = 0
	for j in range(N - 1, 0, -1):
		n = idx[j]
		avl.insert(n)
		(l1_idx, l2_idx) = avl.get_smaller_key(n)
		l1 = n - l1_idx
		if l1_idx != 0:
			l2 = l1_idx - l2_idx
		else:
			l2 = 0
		(r1_idx, r2_idx) = avl.get_greater_key(n)
		r1 = r1_idx - n
		if r1_idx != N + 1:
			r2 = r2_idx - r1_idx
		else:
			r2 = 0
		cnt = (l1 * r2 + r1 * l2) * j
		total += cnt
	print(total)

def __starting_point():
	main()
__starting_point()


class BinaryIndexedTree:

	def __init__(self, size):
		self.data = [0] * (size + 1)
		self.msb = 1 << size.bit_length() - 1

	def add(self, i, w):
		i += 1
		while i < len(self.data):
			self.data[i] += w
			i += i & -i

	def get_sum(self, i):
		res = 0
		while i > 0:
			res += self.data[i]
			i -= i & -i
		return res

	def __getitem__(self, i):
		if isinstance(i, slice):
			return self.get_sum(i.stop) if i.start is None else self.get_sum(i.stop) - self.get_sum(i.start)
		else:
			return 0
	__setitem__ = add

	def bisect_left(self, v):
		i = 0
		k = self.msb
		while k > 0:
			i += k
			if i < len(self.data) and self.data[i] < v:
				v -= self.data[i]
			else:
				i -= k
			k >>= 1
		return i

	def bisect_right(self, v):
		i = 0
		k = self.msb
		while k > 0:
			i += k
			if i < len(self.data) and self.data[i] <= v:
				v -= self.data[i]
			else:
				i -= k
			k >>= 1
		return i
	bisect = bisect_right

def naive(P):

	def it():
		for i in range(len(P) - 1):
			for j in range(i + 1, len(P)):
				yield sorted(P[i:j + 1])[-2]
	return sum(it())

def solve(P):

	def it():
		bit = BinaryIndexedTree(len(P))
		for (cnt, (v, i)) in enumerate(sorted(((v, i) for (i, v) in enumerate(P)), reverse=True)):
			bit[i] += 1
			c = bit.get_sum(i)
			low1 = -1 if c <= 0 else bit.bisect_left(c)
			low2 = -1 if c <= 1 else bit.bisect_left(c - 1)
			up1 = len(P) if c > cnt - 1 else bit.bisect_left(c + 2)
			up2 = len(P) if c > cnt - 2 else bit.bisect_left(c + 3)
			yield (v * ((up1 - i) * (low1 - low2) + (i - low1) * (up2 - up1)))
	return sum(it())
N = int(input())
P = list(map(int, input().split()))
print(solve(P))


import sys
from heapq import heappop, heappush
from operator import itemgetter
from collections import deque, defaultdict, Counter
from bisect import bisect_left, bisect_right
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
INF = float('inf')

class BIT:

	def __init__(self, size):
		self.size = size
		self.tree = [0] * (size + 1)

	def add(self, index):
		while index <= self.size:
			self.tree[index] += 1
			index += index & -index

	def sum(self, index):
		ret = 0
		while index:
			ret += self.tree[index]
			index -= index & -index
		return ret

	def search(self, value):
		i = 0
		s = 0
		step = 1 << self.size.bit_length() - 1
		while step:
			if i + step <= self.size and s + self.tree[i + step] < value:
				i += step
				s += self.tree[i]
			step //= 2
		return i + 1

def sol():
	N = int(input())
	P = [None] + list(map(int, input().split()))
	ans = 0
	pToIndex = {p: i for (i, p) in enumerate(P[1:], 1)}
	tree = BIT(N)
	for p in range(1, N + 1)[::-1]:
		c = pToIndex[p]
		left = tree.sum(c)
		tree.add(c)
		right = N - p - left
		a = tree.search(left - 1) if left >= 2 else 0
		b = tree.search(left) if left >= 1 else 0
		d = tree.search(left + 2) if right >= 1 else N + 1
		e = tree.search(left + 3) if right >= 2 else N + 1
		cnt = 0
		if b != 0:
			cnt += (b - a) * (d - c)
		if d != 0:
			cnt += (e - d) * (c - b)
		ans += cnt * p
	print(ans)
sol()


import sys
stdin = sys.stdin
ni = lambda : int(ns())
nl = lambda : list(map(int, stdin.readline().split()))
nm = lambda : list(map(int, stdin.readline().split()))
ns = lambda : stdin.readline().rstrip()
n = ni()
p = nl()
q = [0] * (n + 1)
for i in range(n):
	q[p[i]] = i + 1
ans = 0
l = [0] + [i for i in range(n + 1)]
r = [i + 1 for i in range(n + 1)] + [n + 1]
for i in range(1, n + 1):
	v = q[i]
	(l1, r1) = (l[v], r[v])
	(l2, r2) = (l[l1], r[r1])
	ans += i * ((v - l1) * (r2 - r1) + (r1 - v) * (l1 - l2))
	l[r1] = l1
	r[l1] = r1
print(ans)


from bisect import bisect_left, bisect_right, insort_right

class CubeSkipList:

	def __init__(self, values=None, sorted_=False, cube=100, seed=42):
		inf = float('inf')
		self.rand_y = seed
		self.cube = cube
		if values is None:
			self.layer2 = [inf]
			self.layer1 = [[]]
			self.layer0 = [[[]]]
		else:
			self.layer2 = layer2 = []
			self.layer1 = layer1 = []
			self.layer0 = layer0 = []
			if not sorted_:
				values.sort()
			rand_depth = self.rand_depth
			l1 = []
			la0 = []
			l0 = []
			for v in values:
				r = rand_depth()
				if r == 0:
					l0.append(v)
				elif r == 1:
					la0.append(l0)
					l0 = []
					l1.append(v)
				else:
					la0.append(l0)
					layer0.append(la0)
					layer1.append(l1)
					l0 = []
					la0 = []
					l1 = []
					layer2.append(v)
			la0.append(l0)
			layer0.append(la0)
			layer1.append(l1)
			layer2.append(inf)

	def rand_depth(self):
		y = self.rand_y
		y ^= y << 13 & 4294967295
		y ^= y >> 17
		y ^= y << 5 & 4294967295
		self.rand_y = y
		if y % self.cube == 0:
			if y % self.cube ** 2 == 0:
				return 2
			return 1
		return 0

	def add(self, x):
		(layer2, layer1, layer0) = (self.layer2, self.layer1, self.layer0)
		r = self.rand_depth()
		if r == 0:
			idx2 = bisect_right(layer2, x)
			idx1 = bisect_right(layer1[idx2], x)
			insort_right(layer0[idx2][idx1], x)
		elif r == 1:
			idx2 = bisect_right(layer2, x)
			l1 = layer1[idx2]
			idx1 = bisect_right(l1, x)
			l1.insert(idx1, x)
			la0 = layer0[idx2]
			l0 = la0[idx1]
			idx0 = bisect_right(l0, x)
			la0.insert(idx1 + 1, l0[idx0:])
			del l0[idx0:]
		else:
			idx2 = bisect_right(layer2, x)
			layer2.insert(idx2, x)
			l1 = layer1[idx2]
			idx1 = bisect_right(l1, x)
			la0 = layer0[idx2]
			l0 = la0[idx1]
			idx0 = bisect_right(l0, x)
			la0.insert(idx1 + 1, l0[idx0:])
			del l0[idx0:]
			layer0.insert(idx2 + 1, la0[idx1 + 1:])
			del la0[idx1 + 1:]
			layer1.insert(idx2 + 1, l1[idx1:])
			del l1[idx1:]

	def remove(self, x):
		raise NotImplementedError
		(layer1, layer0) = (self.layer1, self.layer0)
		idx1 = bisect_left(layer1, x)
		if layer1[idx1] == x:
			del layer1[idx1]
			layer0[idx1] += layer0[idx1 + 1]
			del layer0[idx1 + 1]
		else:
			layer0_idx1 = layer0[idx1]
			del layer0_idx1[bisect_left(layer0_idx1, x)]

	def bisect_left(self, x):
		raise NotImplementedError
		(layer1, layer0) = (self.layer1, self.layer0)
		idx1 = bisect_left(layer1, x)
		res = layer1[idx1]
		if res == x:
			return res
		layer0_idx1 = layer0[idx1]
		if layer0_idx1:
			idx0 = bisect_left(layer0_idx1, x)
			if idx0 == len(layer0_idx1):
				return res
			else:
				return layer0_idx1[idx0]
		else:
			return res

	def search_higher(self, x):
		(layer2, layer1, layer0) = (self.layer2, self.layer1, self.layer0)
		idx2 = bisect_right(layer2, x)
		l1 = layer1[idx2]
		idx1 = bisect_right(l1, x)
		la0 = layer0[idx2]
		l0 = la0[idx1]
		idx0 = bisect_right(l0, x)
		if idx0 == len(l0):
			if idx1 == len(l1):
				return layer2[idx2]
			return l1[idx1]
		return l0[idx0]

	def search_lower(self, x):
		(layer2, layer1, layer0) = (self.layer2, self.layer1, self.layer0)
		idx2 = bisect_left(layer2, x)
		l1 = layer1[idx2]
		idx1 = bisect_left(l1, x)
		la0 = layer0[idx2]
		l0 = la0[idx1]
		idx0 = bisect_left(l0, x)
		if idx0 == 0:
			if idx1 == 0:
				return layer2[idx2 - 1]
			return l1[idx1 - 1]
		return l0[idx0 - 1]

	def pop(self, idx):
		raise NotImplementedError
		(layer1, layer0) = (self.layer1, self.layer0)
		s = -1
		for (i, l0) in enumerate(layer0):
			s += len(l0) + 1
			if s >= idx:
				break
		if s == idx:
			layer0[i] += layer0[i + 1]
			del layer0[i + 1]
			return layer1.pop(i)
		else:
			return layer0[i].pop(idx - s)

	def print(self):
		print(self.layer2)
		print(self.layer1)
		print(self.layer0)

def main():
	n = int(input())
	p = list(map(int, input().split()))
	idx = [0] * n
	for i in range(0, n):
		idx[i] = i
	idx.sort(key=lambda i: -p[i])
	ssl = CubeSkipList()
	ssl.add(-1)
	ssl.add(n)
	ans = 0
	for i in idx:
		nex = ssl.search_higher(i)
		nexnex = ssl.search_higher(nex)
		pre = ssl.search_lower(i)
		prepre = ssl.search_lower(pre)
		if prepre != float('inf'):
			ans += p[i] * (pre - prepre) * (nex - i)
		if nexnex != float('inf'):
			ans += p[i] * (i - pre) * (nexnex - nex)
		ssl.add(i)
	print(ans)
main()


import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
(n, *p) = map(int, read().split())
ans = 0
l = list(range(n))
r = list(range(n))
memo = [-1] * (n + 1)
for (i, pp) in enumerate(p):
	memo[pp] = i
for (i, idx) in enumerate(memo[1:], 1):
	l1 = idx - 1
	r1 = idx + 1
	while l1 >= 0 and l1 != l[l1]:
		l1 = l[l1]
	while r1 < n and r1 != r[r1]:
		r1 = r[r1]
	l[idx] = l1
	r[idx] = r1
	if l1 != -1:
		l2 = l1 - 1
		while l2 >= 0 and l2 != l[l2]:
			l2 = l[l2]
		ans += (l1 - l2) * (r1 - idx) * i
	if r1 != n:
		r2 = r1 + 1
		while r2 < n and r2 != r[r2]:
			r2 = r[r2]
		ans += (r2 - r1) * (idx - l1) * i
print(ans)


from heapq import heappush, heappop
N = int(input())
P = [int(i) for i in input().split()]
dpl = [[] for _ in range(N)]
dpr = [[] for _ in range(N)]
q = []
for i in range(N - 1, -1, -1):
	L = []
	while len(q) > 0 and q[0][0] < P[i]:
		(v, j) = heappop(q)
		if len(dpl[j]) == 0:
			L.append([v, j])
		dpl[j].append(i)
	for (v, j) in L:
		heappush(q, [v, j])
	heappush(q, [P[i], i])
q = []
for i in range(N):
	L = []
	while len(q) > 0 and q[0][0] < P[i]:
		(v, j) = heappop(q)
		if len(dpr[j]) == 0:
			L.append([v, j])
		dpr[j].append(i)
	for (v, j) in L:
		heappush(q, [v, j])
	heappush(q, [P[i], i])
for i in range(N):
	for _ in range(2 - len(dpl[i])):
		dpl[i].append(-1)
	for _ in range(2 - len(dpr[i])):
		dpr[i].append(N)
	dpl[i].sort()
	dpr[i].sort()
ret = 0
for i in range(N):
	ret += (dpl[i][1] - dpl[i][0]) * (dpr[i][0] - i) * P[i]
	ret += (i - dpl[i][1]) * (dpr[i][1] - dpr[i][0]) * P[i]
print(ret)


import sys
input = sys.stdin.readline
N = int(input())
P = list(map(int, input().split()))

class SegmentTree:

	def __init__(self, data, op, default):
		N = len(data)
		self.N = N
		self.op = op
		self.default = default
		self.l = 2 ** (N - 1).bit_length()
		self.data = [default] * self.l + data + [default] * (self.l - N)
		for i in range(self.l - 1, 0, -1):
			self.data[i] = op(self.data[2 * i], self.data[2 * i + 1])

	def get_data(self):
		return self.data[self.l:self.l + self.N]

	def set(self, i, val):
		i += self.l
		self.data[i] = val
		i = i // 2
		while i > 0:
			self.data[i] = self.op(self.data[2 * i], self.data[2 * i + 1])
			i = i // 2

	def get(self, i, j):
		i += self.l
		j += self.l
		s = self.default
		while j - i > 0:
			if i & 1:
				s = self.op(s, self.data[i])
				i += 1
			if j & 1:
				s = self.op(s, self.data[j - 1])
				j -= 1
			i = i // 2
			j = j // 2
		return s
P2 = [[[p, i], [0, 0]] for (i, p) in enumerate(P)]
max2 = lambda x, y: sorted(x + y, reverse=True)[:2]
seg = SegmentTree(P2, max2, [[0, 0], [0, 0]])
cand = [[0, N]]
ans = 0
visited = set([])
while cand:
	temp = []
	for (l, r) in cand:
		if r - l < 2:
			continue
		if (l, r) in visited:
			continue
		visited.add((l, r))
		((m1, i1), (m2, i2)) = seg.get(l, r)
		(i1, i2) = (i1, i2) if i1 < i2 else (i2, i1)
		ans += m2 * (i1 - l + 1) * (r - i2)
		temp.append([l, i2])
		temp.append([i1 + 1, r])
	cand = temp
print(ans)


from bisect import bisect_left
import array
n = int(input())
p = []
for (i, x) in enumerate(map(int, input().split())):
	p.append([x, i])
p.sort(reverse=True)
s = array.array('i', [-1, -1, p[0][1], n, n])
ans = 0
i = 2
for (a, x) in p[1:]:
	t = bisect_left(s, x)
	ans += a * ((x - s[t - 1]) * (s[t + 1] - s[t]) + (s[t] - x) * (s[t - 1] - s[t - 2]))
	s.insert(t, x)
	i += 1
print(ans)


from bisect import bisect_left, bisect_right

class OrderedSet:

	def __init__(self, a):
		self.c = {}
		self.a_sort = sorted(list(set(a)))
		for (i, a) in enumerate(self.a_sort):
			self.c[a] = i + 1
		self.r = {v: k for (k, v) in self.c.items()}
		self.size = len(self.c)
		self.tree = [0] * (self.size + 1)
		self.num = [0] * self.size
		self.all_count = 0

	def _sum(self, index):
		s = 0
		while index:
			s += self.tree[index]
			index -= index & -index
		return s

	def insert(self, x, k=1):
		index = self.c[x]
		self.num[index - 1] += k
		while index <= self.size:
			self.tree[index] += k
			index += index & -index
		self.all_count += k

	def erase(self, x, k=1):
		self.insert(x, k=-k)

	def count(self, x):
		return self.num[self.c[x] - 1]

	def get_kth_bottom(self, k):
		if k <= 0:
			return None
		elif self.all_count < k:
			return None
		else:
			i = 0
			s = 0
			step = 1 << self.size.bit_length() - 1
			while step:
				if i + step <= self.size and s + self.tree[i + step] < k:
					i += step
					s += self.tree[i]
				step >>= 1
			return self.r[i + 1]

	def get_kth_top(self, k):
		return self.get_kth_bottom(self.all_count - k + 1)

	def lower_bound(self, x):
		p = bisect_left(self.a_sort, x)
		if p == 0:
			k = 1
		else:
			k = self._sum(p) + 1
		return self.get_kth_bottom(k)

	def upper_bound(self, x):
		p = bisect_right(self.a_sort, x)
		if p == 0:
			return None
		else:
			k = self._sum(p)
			return self.get_kth_bottom(k)

def resolve():
	N = int(input())
	A = list(map(int, input().split()))
	P = [0] * (N + 1)
	for i in range(N):
		P[A[i]] = i + 1
	OS = OrderedSet(P)
	ans = 0
	for i in range(N, 0, -1):
		p = P[i]
		c = OS.lower_bound(p)
		d = None if c is None else OS.lower_bound(c + 1)
		b = OS.upper_bound(p)
		a = None if b is None else OS.upper_bound(b - 1)
		a = a if a is not None else 0
		d = d if d is not None else N + 1
		if b is None:
			if c is not None:
				ans += i * p * (d - c)
		elif c is None:
			ans += i * (b - a) * (N - p + 1)
		else:
			ans += i * ((b - a) * (c - p) + (p - b) * (d - c))
		OS.insert(p)
	print(ans)
resolve()


from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
import pprint
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 13

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def I():
	return int(sys.stdin.buffer.readline())

def LS():
	return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()

def S():
	return sys.stdin.buffer.readline().rstrip().decode('utf-8')

def IR(n):
	return [I() for i in range(n)]

def LIR(n):
	return [LI() for i in range(n)]

def SR(n):
	return [S() for i in range(n)]

def LSR(n):
	return [LS() for i in range(n)]

def SRL(n):
	return [list(S()) for i in range(n)]

def MSRL(n):
	return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007

class BIT:

	def __init__(self, size):
		self.bit = [0] * size
		self.size = size
		self.total = 0

	def add(self, i, w):
		x = i + 1
		self.total += w
		while x <= self.size:
			self.bit[x - 1] += w
			x += x & -x
		return

	def sum(self, i):
		res = 0
		x = i + 1
		while x:
			res += self.bit[x - 1]
			x -= x & -x
		return res

	def interval_sum(self, i, j):
		return self.sum(j - 1) - self.sum(i - 1)

	def search(self, k):
		if k > self.total or k <= 0:
			return -1
		step = 1 << self.size.bit_length() - 1
		now_index = 0
		ret = 0
		while step:
			if now_index + step < self.size and ret + self.bit[now_index + step - 1] < k:
				ret += self.bit[now_index + step - 1]
				now_index += step
			step >>= 1
		return now_index
n = I()
P = LI()
val_idx = {P[j]: j + 1 for j in range(n)}
bit = BIT(n + 2)
bit.add(n + 1, 1)
bit.add(0, 1)
ans = 0
for k in range(n, 0, -1):
	idx = val_idx[k]
	m = bit.sum(idx)
	l1 = bit.search(m - 1)
	l2 = bit.search(m)
	r1 = bit.search(m + 1)
	r2 = bit.search(m + 2)
	if l1 >= 0:
		ans += (l2 - l1) * (r1 - idx) * k
	if r2 >= 0:
		ans += (idx - l2) * (r2 - r1) * k
	bit.add(idx, 1)
print(ans)


class SegTree:

	def __init__(self, N, e=0, operator_func=lambda x, y: x + y):
		self.e = e
		self.N = N
		bitlen = N.bit_length()
		self.size = 2 ** (bitlen if N & N - 1 else bitlen - 1)
		self.node = [self.e] * (2 * self.size)
		self.op = operator_func

	def set_list(self, l):
		for (i, j) in enumerate(l):
			self.node[i + self.size - 1] = j
		for i in range(self.size - 1)[::-1]:
			self.node[i] = self.op(self.node[2 * i + 1], self.node[2 * i + 2])

	def update(self, k, x):
		k += self.size - 1
		self.node[k] = x
		while k >= 0:
			k = (k - 1) // 2
			self.node[k] = self.op(self.node[2 * k + 1], self.node[2 * k + 2])

	def get(self, l, r):
		x = self.e
		l += self.size
		r += self.size
		(a, b) = ([], [])
		while l < r:
			if l & 1:
				a += [l - 1]
				l += 1
			if r & 1:
				r -= 1
				b += [r - 1]
			l >>= 1
			r >>= 1
		for i in a + b[::-1]:
			x = self.op(x, self.node[i])
		return x

	def bisect_left(self, x):
		if x > self.node[0]:
			return self.N
		(p, ans) = (0, 0)
		node_size = 2 * self.size - 1
		x -= 1
		while p < node_size:
			ans = p - (self.size - 1)
			(p1, p2) = (2 * p + 1, 2 * p + 2)
			if p1 < node_size and self.node[p1] <= x:
				x -= self.node[p1]
				p = p2
			else:
				p = p1
		return ans + 1
N = int(input())
l = [(j, i) for (i, j) in enumerate(map(int, input().split()))]
l.sort(key=lambda x: -x[0])
tree = SegTree(N)
ans = 0
for (n, (value, idx)) in enumerate(l, start=1):
	v = tree.get(0, idx + 1)
	a = tree.bisect_left(v - 1) if v > 1 else 0
	b = tree.bisect_left(v - 0) if v else 0
	c = tree.bisect_left(v + 1) if n - v > 1 else N + 1
	d = tree.bisect_left(v + 2) if n - v > 2 else N + 1
	tree.update(idx, 1)
	idx += 1
	ans += ((b - a) * (c - idx) + (d - c) * (idx - b)) * value
print(ans)


import sys
sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline

class BinaryIndexedTree:

	def __init__(self, n):
		self.n = n
		self.data = [0] * (n + 1)

	def add(self, i, x):
		while i <= self.n:
			self.data[i] += x
			i += i & -i

	def sum(self, i):
		res = 0
		while i:
			res += self.data[i]
			i -= i & -i
		return res

	def bisect_left(self, w):
		if w <= 0:
			return 0
		i = 0
		k = 1 << self.n.bit_length() - 1
		while 0 < k:
			if i + k <= self.n and self.data[i + k] < w:
				w -= self.data[i + k]
				i += k
			k >>= 1
		return i + 1

def solve():
	N = int(rl())
	P = list(map(int, rl().split()))
	p_to_idx = [0] * (N + 1)
	for (i, x) in enumerate(P):
		p_to_idx[x] = i + 1
	bit = BinaryIndexedTree(N)
	ans = 0
	for pi in range(N, 0, -1):
		idx = p_to_idx[pi]
		left = bit.sum(idx)
		bit.add(idx, 1)
		right = N - pi - left
		l0 = bit.bisect_left(left - 1) if 2 <= left else 0
		l1 = bit.bisect_left(left) if 1 <= left else 0
		r0 = bit.bisect_left(left + 2) if 1 <= right else N + 1
		r1 = bit.bisect_left(left + 3) if 2 <= right else N + 1
		cnt = 0
		if l1 != 0:
			cnt += (l1 - l0) * (r0 - idx)
		if r0 != 0:
			cnt += (r1 - r0) * (idx - l1)
		ans += pi * cnt
	print(ans)
solve()


import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
(N, *P) = map(int, read().split())
INF = N + 100
P = [INF, INF] + P + [INF, INF]
x_to_i = [0] * (INF + 1)
for (i, x) in enumerate(P):
	x_to_i[x] = i
left = list(range(N + 4))
right = list(range(N + 4))
filled = [False] * (N + 4)
answer = 0
for (x, i) in enumerate(x_to_i[1:N + 1], 1):
	filled[i] = True
	L = left[i - 1] if filled[i - 1] else i
	R = right[i + 1] if filled[i + 1] else i
	right[L] = R
	left[R] = L
	c = i
	b = L - 1
	d = R + 1
	a = left[L - 2] - 1 if filled[L - 2] else L - 2
	e = right[R + 2] + 1 if filled[R + 2] else R + 2
	coef = 0
	if b >= 2:
		coef += (b - a) * (d - c)
	if d <= N + 1:
		coef += (e - d) * (c - b)
	answer += x * coef
print(answer)


def resolve():
	N = int(input())
	A = list(map(int, input().split()))
	P = [0] * (N + 1)
	for (i, a) in enumerate(A):
		P[a] = i
	l_idx = list(range(-1, N - 1)) + [-1, -1]
	r_idx = list(range(1, N + 1)) + [N, N]
	ans = 0
	for p in range(1, N + 1):
		x = P[p]
		l1 = l_idx[x]
		l2 = l_idx[l1]
		r1 = r_idx[x]
		r2 = r_idx[r1]
		cmb = (x - l1) * (r2 - r1) + (l1 - l2) * (r1 - x)
		ans += p * cmb
		l_idx[r1] = l1
		r_idx[l1] = r1
	print(ans)
resolve()


def main():
	import sys
	input = sys.stdin.readline
	sys.setrecursionlimit(10 ** 7)
	from collections import Counter, deque
	from itertools import combinations, permutations, accumulate, groupby, product
	from bisect import bisect_left, bisect_right
	from heapq import heapify, heappop, heappush
	import math
	n = int(input())
	p = list(map(int, input().split()))
	f = [0] * (n + 1)
	for i in range(n):
		f[p[i]] = i + 1
	l = [0] + [i for i in range(n + 1)]
	r = [i + 1 for i in range(n + 1)] + [n + 1]
	res = 0
	for i in range(1, n + 1):
		x = f[i]
		(l1, r1) = (l[x], r[x])
		(l2, r2) = (l[l1], r[r1])
		res += ((l1 - l2) * (r1 - x) + (x - l1) * (r2 - r1)) * i
		(l[r1], r[l1]) = (l1, r1)
	print(res)
main()


class BIT:

	def __init__(self, size):
		self.size = size
		self.data = [0] * (size + 1)

	def add(self, index, value=1):
		while index <= self.size:
			self.data[index] += value
			index += index & -index

	def sum(self, index):
		ret = 0
		while index:
			ret += self.data[index]
			index -= index & -index
		return ret

	def search(self, val):
		i = 0
		s = 0
		step = 1 << self.size.bit_length() - 1
		while step:
			if i + step <= self.size and s + self.data[i + step] < val:
				i += step
				s += self.data[i]
			step //= 2
		return i + 1

def sol():
	N = int(input())
	P = [None] + list(map(int, input().split()))
	pToI = {p: i for (i, p) in enumerate(P[1:], 1)}
	tree = BIT(N)
	ans = 0
	for p in range(1, N + 1)[::-1]:
		i = pToI[p]
		left = tree.sum(i)
		tree.add(i)
		right = N - p - left
		L1 = tree.search(left - 1) if left >= 2 else 0
		L2 = tree.search(left) if left >= 1 else 0
		R1 = tree.search(left + 2) if right >= 1 else N + 1
		R2 = tree.search(left + 3) if right >= 2 else N + 1
		cnt = 0
		if L2 != 0:
			cnt += (L2 - L1) * (R1 - i)
		if R1 != 0:
			cnt += (R2 - R1) * (i - L2)
		ans += cnt * p
	print(ans)
sol()


import sys
from heapq import heappush, heappop
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007

class BIT:

	def __init__(self, n):
		self.n = n
		self.data = [0] * (n + 1)
		self.step = pow(2, n.bit_length() - 1)

	def add(self, i, x=1):
		i += 1
		while i <= self.n:
			self.data[i] += x
			i += i & -i

	def get_sum(self, i):
		i += 1
		x = 0
		while i > 0:
			x += self.data[i]
			i -= i & -i
		return x

	def get_sum_range(self, l, r):
		return self.get_sum(r - 1) - self.get_sum(l - 1)

	def lower_bound(self, x):
		if x <= 0:
			return 0
		i = 0
		k = self.step
		while k:
			if i + k <= self.n and self.data[i + k] < x:
				x -= self.data[i + k]
				i += k
			k >>= 1
		return i

def main():
	(N, *P) = map(int, read().split())
	index = [0] * (N + 1)
	for (i, p) in enumerate(P):
		index[p] = i
	bit = BIT(N)
	ans = 0
	for n in range(N, 0, -1):
		i = index[n]
		bit.add(i)
		x = bit.get_sum(i)
		left1 = left2 = -1
		right1 = right2 = N
		if x - 2 > 0:
			left2 = bit.lower_bound(x - 2)
		if x - 1 > 0:
			left1 = bit.lower_bound(x - 1)
		if x + 1 <= N - n + 1:
			right1 = bit.lower_bound(x + 1)
		if x + 2 <= N - n + 1:
			right2 = bit.lower_bound(x + 2)
		ans += ((left1 - left2) * (right1 - i) + (right2 - right1) * (i - left1)) * n
	print(ans)
	return
main()


n = int(input())
p = list(map(int, input().split()))
pi = sorted(zip(p, range(n)))
left = {i: i - 1 for i in range(n)}
right = {i: i + 1 for i in range(n)}
left[-1] = -1
right[n] = n
ret = 0
for (p, i) in pi:
	ret += p * (left[i] - left[left[i]]) * (right[i] - i)
	ret += p * (i - left[i]) * (right[right[i]] - right[i])
	(l, r) = (left[i], right[i])
	right[l] = r
	left[r] = l
print(ret)


N = int(input())
P = list(map(int, input().split()))
R = list(range(N))
L = list(range(N))
I = [-1] * (N + 1)
for (i, p) in enumerate(P):
	I[p] = i
ans = 0
for (n, idx) in enumerate(I[1:], 1):
	l = idx - 1
	while l >= 0 and l != L[l]:
		l = L[l]
	r = idx + 1
	while r < N and r != R[r]:
		r = R[r]
	L[idx] = l
	R[idx] = r
	if l != -1:
		l2 = l - 1
		while l2 >= 0 and l2 != L[l2]:
			l2 = L[l2]
		ans += n * (l - l2) * (r - idx)
	if r != N:
		r2 = r + 1
		while r2 < N and r2 != R[r2]:
			r2 = R[r2]
		ans += n * (idx - l) * (r2 - r)
print(ans)


class Node:

	def __init__(self, key=None):
		self.key = key
		self.height = 1
		self.parent = None
		self.left = None
		self.right = None

def get_height(t):
	return 0 if t is None else t.height

def get_balance(t):
	return get_height(t.left) - get_height(t.right)

def update_height(t):
	left_height = get_height(t.left)
	right_height = get_height(t.right)
	if left_height >= right_height:
		t.height = left_height + 1
	else:
		t.height = right_height + 1

class AVL:

	def __init__(self):
		self.root = Node()

	def insert(self, key):
		if self.root.key is None:
			self.root.key = key
			return
		cursor = self.root
		while cursor:
			p = cursor
			if key == cursor.key:
				return
			elif key < cursor.key:
				cursor = cursor.left
			else:
				cursor = cursor.right
		new_node = Node(key)
		new_node.parent = p
		if key < p.key:
			p.left = new_node
		else:
			p.right = new_node
		cursor = p
		while cursor:
			balance = get_balance(cursor)
			if balance == 0:
				break
			elif balance == 2:
				if key < cursor.left.key:
					self.rotate_r(cursor)
				else:
					self.rotate_lr(cursor)
				break
			elif balance == -2:
				if key > cursor.right.key:
					self.rotate_l(cursor)
				else:
					self.rotate_rl(cursor)
				break
			else:
				update_height(cursor)
				cursor = cursor.parent

	def rotate_r(self, n):
		p = n.parent
		c = n.left
		gc = n.left.right
		if gc is not None:
			n.left = gc
			gc.parent = n
		else:
			n.left = None
		c.right = n
		n.parent = c
		if p is not None:
			if p.right == n:
				p.right = c
			else:
				p.left = c
			c.parent = p
		else:
			self.root = c
			self.root.parent = None
		update_height(n)
		update_height(c)

	def rotate_l(self, n):
		p = n.parent
		c = n.right
		gc = n.right.left
		if gc is not None:
			n.right = gc
			gc.parent = n
		else:
			n.right = None
		c.left = n
		n.parent = c
		if p is not None:
			if p.left == n:
				p.left = c
			else:
				p.right = c
			c.parent = p
		else:
			self.root = c
			self.root.parent = None
		update_height(n)
		update_height(c)

	def rotate_rl(self, n):
		p = n.parent
		c = n.right
		gc = n.right.left
		if gc.left and gc.right:
			n.right = gc.left
			c.left = gc.right
			gc.left.parent = n
			gc.right.parent = c
		elif gc.left:
			n.right = gc.left
			gc.left.parent = n
			c.left = None
		elif gc.right:
			c.left = gc.right
			gc.right.parent = c
			n.right = None
		else:
			n.right = None
			c.left = None
		gc.left = n
		gc.right = c
		n.parent = gc
		c.parent = gc
		if p is not None:
			if p.left == n:
				p.left = gc
			else:
				p.right = gc
			gc.parent = p
		else:
			self.root = gc
			self.root.parent = None
		update_height(n)
		update_height(c)
		update_height(gc)

	def rotate_lr(self, n):
		p = n.parent
		c = n.left
		gc = n.left.right
		if gc.left and gc.right:
			c.right = gc.left
			n.left = gc.right
			gc.left.parent = c
			gc.right.parent = n
		elif gc.left:
			c.right = gc.left
			gc.left.parent = c
			n.left = None
		elif gc.right:
			n.left = gc.right
			gc.right.parent = n
			c.right = None
		else:
			n.left = None
			c.right = None
		gc.left = c
		gc.right = n
		c.parent = gc
		n.parent = gc
		if p is not None:
			if p.left == n:
				p.left = gc
			else:
				p.right = gc
			gc.parent = p
		else:
			self.root = gc
			self.root.parent = None
		update_height(n)
		update_height(c)
		update_height(gc)

	def find(self, key):
		cursor = self.root
		while cursor:
			if cursor.key == key:
				return cursor
			if key < cursor.key:
				cursor = cursor.left
			else:
				cursor = cursor.right
		return None

	def next_greater_key(self, cursor):
		if cursor is None:
			return None
		if cursor.right:
			cursor = cursor.right
			while cursor.left:
				cursor = cursor.left
			return cursor
		elif cursor.parent.left == cursor:
			return cursor.parent
		elif cursor.parent.right == cursor:
			while cursor.parent and cursor.parent.right == cursor:
				cursor = cursor.parent
			if cursor.parent:
				return cursor.parent
		else:
			return None

	def next_smaller_key(self, cursor):
		if cursor is None:
			return None
		if cursor.left:
			cursor = cursor.left
			while cursor.right:
				cursor = cursor.right
			return cursor
		elif cursor.parent.right == cursor:
			return cursor.parent
		elif cursor.parent.left == cursor:
			while cursor.parent and cursor.parent.left == cursor:
				cursor = cursor.parent
			if cursor.parent:
				return cursor.parent
		else:
			return None

	def get_smaller_key(self, key):
		cursor = self.find(key)
		l1 = self.next_smaller_key(cursor)
		l2 = self.next_smaller_key(l1)
		if l2 is None:
			l2 = 0
		else:
			l2 = l2.key
		return (l1.key, l2)

	def get_greater_key(self, key):
		cursor = self.find(key)
		r1 = self.next_greater_key(cursor)
		r2 = self.next_greater_key(r1)
		if r2 is None:
			r2 = 0
		else:
			r2 = r2.key
		return (r1.key, r2)

def main():
	N = int(input())
	P = map(int, input().split())
	idx = [-1] * (N + 1)
	for (i, v) in enumerate(P, 1):
		idx[v] = i
	avl = AVL()
	for i in [0, idx[N], N + 1]:
		avl.insert(i)
	total = 0
	for j in range(N - 1, 0, -1):
		n = idx[j]
		avl.insert(n)
		(l1_idx, l2_idx) = avl.get_smaller_key(n)
		l1 = n - l1_idx
		if l1_idx != 0:
			l2 = l1_idx - l2_idx
		else:
			l2 = 0
		(r1_idx, r2_idx) = avl.get_greater_key(n)
		r1 = r1_idx - n
		if r1_idx != N + 1:
			r2 = r2_idx - r1_idx
		else:
			r2 = 0
		cnt = (l1 * r2 + r1 * l2) * j
		total += cnt
	print(total)

def __starting_point():
	main()
__starting_point()


import sys
input = sys.stdin.buffer.readline

def main():
	N = int(input())
	p = list(map(int, input().split()))
	nl = [0] * N
	for (i, num) in enumerate(p):
		nl[num - 1] = i + 1
	nl.reverse()

	class BinaryIndexedTree:

		def __init__(self, size, default):
			self.size = size
			self.default = default
			self.BIT = [default] * (self.size + 1)

		def BIT_segfunc(self, x, y):
			return x + y

		def BIT_query(self, idx):
			ret = self.default
			while idx > 0:
				ret = self.BIT_segfunc(ret, self.BIT[idx])
				idx -= idx & -idx
			return ret

		def BIT_update(self, idx, x):
			while idx <= self.size:
				self.BIT[idx] = self.BIT_segfunc(self.BIT[idx], x)
				idx += idx & -idx
			return

		def BIT_range(self, x, y):
			return self.BIT_query(y) - self.BIT_query(x)

		def BIT_print(self):
			print(self.BIT)

		def BIT_search(self, x):
			i = 0
			s = 0
			step = 1 << self.size.bit_length() - 1
			while step:
				if i + step <= self.size and s + self.BIT[i + step] < x:
					i += step
					s += self.BIT[i]
				step >>= 1
			return i + 1
	BIT = BinaryIndexedTree(N, 0)
	ans = 0
	for (i, num) in enumerate(nl):
		l = BIT.BIT_query(num)
		BIT.BIT_update(num, 1)
		r = i - l
		a = BIT.BIT_search(l - 1) if l >= 2 else 0
		b = BIT.BIT_search(l) if l >= 1 else 0
		d = BIT.BIT_search(l + 2) if r >= 1 else N + 1
		e = BIT.BIT_search(l + 3) if r >= 2 else N + 1
		ret = 0
		if b != 0:
			ret += (b - a) * (d - num)
		if d != 0:
			ret += (e - d) * (num - b)
		ans += ret * (N - i)
	print(ans)
main()


class BIT:

	def __init__(self, n):
		self.size = n
		self.tree = [0] * (n + 1)
		self.depth = n.bit_length()

	def sum(self, i):
		s = 0
		while i > 0:
			s += self.tree[i]
			i -= i & -i
		return s

	def add(self, i, x):
		while i <= self.size:
			self.tree[i] += x
			i += i & -i

	def lower_bound(self, x):
		sum_ = 0
		pos = 0
		for i in range(self.depth + 1)[::-1]:
			k = pos + (1 << i)
			if k <= self.size and sum_ + self.tree[k] < x:
				sum_ += self.tree[k]
				pos += 1 << i
		return (pos + 1, sum_)
N = int(input())
l = [(j, i) for (i, j) in enumerate(map(int, input().split()))]
l.sort(key=lambda x: -x[0])
tree = BIT(N)
m = [0] * N
ans = 0
for (value, idx) in l:
	v = tree.sum(idx + 1)
	a = tree.lower_bound(v - 1)[0] if v > 1 else 0
	b = tree.lower_bound(v - 0)[0] if v else 0
	c = tree.lower_bound(v + 1)[0]
	d = tree.lower_bound(v + 2)[0]
	tree.add(idx + 1, 1)
	idx += 1
	ans += ((b - a) * (c - idx) + (d - c) * (idx - b)) * value
print(ans)


def examA():
	N = I()
	ans = 0
	print(ans)
	return

def examB():
	ans = 0
	print(ans)
	return

def examC():
	ans = 0
	print(ans)
	return

def examD():
	ans = 0
	print(ans)
	return

def examE():

	class Bit:

		def __init__(self, n):
			self.size = n
			self.tree = [0] * (n + 1)
			return

		def sum(self, i):
			s = 0
			while i > 0:
				s += self.tree[i]
				i -= i & -i
			return s

		def add(self, i, x=1):
			while i <= self.size:
				self.tree[i] += x
				i += i & -i
			return

		def search(self, x):
			i = 0
			s = 0
			step = 1 << self.size.bit_length() - 1
			while step:
				if i + step <= self.size and s + self.tree[i + step] < x:
					i += step
					s += self.tree[i]
				step >>= 1
			return i + 1

		def debug(self, k):
			return [self.sum(i) for i in range(k)]
	N = I()
	P = LI()
	Order = [[i + 1] for i in range(N)]
	for (i, p) in enumerate(P):
		Order[i].append(p)
	Order.sort(key=lambda x: x[1], reverse=True)
	ans = 0
	bit = Bit(N + 2)
	for (i, p) in Order:
		L = bit.sum(i)
		R = bit.sum(N) - L
		bit.add(i)
		(l0, l1, r0, r1) = (0, 0, N + 1, N + 1)
		if L >= 2:
			l0 = bit.search(L - 1)
		if L >= 1:
			l1 = bit.search(L)
		if R >= 1:
			r0 = bit.search(L + 2)
		if R >= 2:
			r1 = bit.search(L + 3)
		cnt = 0
		if l1 > 0:
			cnt += (l1 - l0) * (r0 - i)
		if r0 > 0:
			cnt += (i - l1) * (r1 - r0)
		ans += cnt * p
	print(ans)
	return

def examF():

	def bfs(n, e, S):
		W = [0] * 2 ** n
		cur = 1
		que = deque()
		que.append(e)
		while cur < 2 ** n:
			now = que.popleft()
			depth = W[now]
			if S[now] <= S[cur]:
				return 'No'
			for ne in range(n - depth):
				cur += 1
				W[now + 1 + ne] = depth + 1
				que.append(now + 1 + ne)
		return 'Yes'
	N = I()
	S = LI()
	S.sort(reverse=True)
	ans = bfs(N, 0, S)
	print(ans)
	return
import sys, copy, bisect, itertools, heapq, math
from heapq import heappop, heappush, heapify
from collections import Counter, defaultdict, deque

def I():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LSI():
	return list(map(str, sys.stdin.readline().split()))

def LS():
	return sys.stdin.readline().split()

def SI():
	return sys.stdin.readline().strip()
global mod, mod2, inf, alphabet
mod = 10 ** 9 + 7
mod2 = 998244353
inf = 10 ** 18
alphabet = [chr(ord('a') + i) for i in range(26)]
examE()


n = int(input())
p = list(map(int, input().split()))
pos_list = [0] * n
for (index, i) in enumerate(p, 0):
	pos_list[i - 1] = index
left_next_index = list(range(-1, n - 1)) + [-1, -1]
right_next_index = list(range(1, n + 1)) + [n, n]
answer = 0
for i in range(1, n):
	index = pos_list[i - 1]
	l1 = left_next_index[index]
	l2 = left_next_index[l1]
	r1 = right_next_index[index]
	r2 = right_next_index[r1]
	answer += i * ((index - l1) * (r2 - r1) + (r1 - index) * (l1 - l2))
	left_next_index[r1] = l1
	right_next_index[l1] = r1
print(answer)


n = int(input())
aa = list(map(int, input().split()))
ans = 0
pos = [0] * (n + 1)
for (i, a) in enumerate(aa):
	pos[a] = i + 2
Lnext = [1, 1] + list(range(1, n + 1)) + [n, n]
Rnext = [3, 3] + list(range(3, n + 3)) + [n + 2, n + 2]
for a in range(1, n + 1):
	i = pos[a]
	l0 = Lnext[i]
	l1 = Lnext[l0]
	r0 = Rnext[i]
	r1 = Rnext[r0]
	ans += a * ((l0 - l1) * (r0 - i) + (i - l0) * (r1 - r0))
	Lnext[r0] = l0
	Rnext[l0] = r0
print(ans)


from sys import stdin
n = int(stdin.readline().rstrip())
p = list(map(int, stdin.readline().rstrip().split()))

def get_nexts(p):
	(d, e) = ([n for i in range(n)], [n for i in range(n)])
	(stack1, stack2) = ([], [])
	for i in range(n):
		while stack2 and p[stack2[-1]] < p[i]:
			idx = stack2.pop()
			e[idx] = i
		to_append = []
		while stack1 and p[stack1[-1]] < p[i]:
			idx = stack1.pop()
			d[idx] = i
			to_append.append(idx)
		while to_append:
			stack2.append(to_append.pop())
		stack1.append(i)
	(dist1, dist2) = ([], [])
	for i in range(n):
		dist1.append(d[i] - i)
		dist2.append(e[i] - d[i])
	return (dist1, dist2)
(dist1, dist2) = get_nexts(p)
(dist3, dist4) = get_nexts(p[::-1])
ans = 0
for i in range(n):
	ans += (dist1[i] * dist4[n - 1 - i] + dist2[i] * dist3[n - 1 - i]) * p[i]
print(ans)


from collections import deque
from bisect import bisect_left
N = int(input())
P = list(map(int, input().split()))
big = []
for k in range(N):
	big.append((P[k], k + 1))
big.sort(key=lambda x: x[0], reverse=True)
big = deque(big)
item = big.popleft()
done = [0, 0, item[1], N + 1, N + 1]
ans = 0
while big:
	item = big.popleft()
	index = item[1]
	num = item[0]
	i = bisect_left(done, index)
	done.insert(i, index)
	ans += num * ((done[i + 2] - done[i + 1]) * (index - done[i - 1]) + (done[i - 1] - done[i - 2]) * (done[i + 1] - index))
print(ans)


N = int(input())
P = list(enumerate(list(map(int, input().split()))))
P = sorted(P, key=lambda x: x[1])
before_idx = list(range(-1, N - 1)) + [-1, -1]
next_idx = list(range(1, N + 1)) + [N, N]
ans = 0
for (i, p) in P:
	il1 = before_idx[i]
	il2 = before_idx[il1]
	ir1 = next_idx[i]
	ir2 = next_idx[ir1]
	ans += p * ((i - il1) * (ir2 - ir1) + (ir1 - i) * (il1 - il2))
	before_idx[ir1] = il1
	next_idx[il1] = ir1
print(ans)


import bisect

class SqrtSet:

	def __init__(self, block_limit=201):
		self.key = []
		self.child = [[]]
		self.block_limit = block_limit

	def search_lower(self, key):
		if key is None:
			return None
		ret = None
		i = bisect.bisect_left(self.key, key)
		if i != 0:
			ret = self.key[i - 1]
		block = self.child[i]
		i = bisect.bisect_left(block, key)
		if i != 0:
			ret = block[i - 1]
		return ret

	def search_higher(self, key):
		if key is None:
			return None
		ret = None
		i = bisect.bisect_right(self.key, key)
		if i != len(self.key):
			ret = self.key[i]
		block = self.child[i]
		i = bisect.bisect_right(block, key)
		if i != len(block):
			ret = block[i]
		return ret

	def insert(self, key):
		i = bisect.bisect(self.key, key)
		block = self.child[i]
		bisect.insort(block, key)
		if len(block) == self.block_limit:
			sep = self.block_limit // 2
			self.key.insert(i, block[sep])
			self.child.insert(i + 1, block[sep + 1:])
			self.child[i] = block[:sep]

	def dump(self):
		for b in self.child:
			print(len(b), end=' ')
		print('')

def main():
	n = int(input())
	p = list(map(int, input().split()))
	idx = [0] * n
	for i in range(0, n):
		idx[i] = i
	idx.sort(key=lambda i: -p[i])
	t = SqrtSet()
	t.insert(-1)
	t.insert(n)
	ans = 0
	for i in idx:
		nex = t.search_higher(i)
		nexnex = t.search_higher(nex)
		pre = t.search_lower(i)
		prepre = t.search_lower(pre)
		if prepre != None:
			ans += p[i] * (pre - prepre) * (nex - i)
		if nexnex != None:
			ans += p[i] * (i - pre) * (nexnex - nex)
		t.insert(i)
	print(ans)
main()


from operator import itemgetter

def solve(n, ppp):
	qqq = sorted(enumerate(ppp), key=itemgetter(1))
	left_next_index = list(range(-1, n - 1)) + [-1, -1]
	right_next_index = list(range(1, n + 1)) + [n, n]
	ans = 0
	for (i, p) in qqq:
		l2 = left_next_index[i]
		l1 = left_next_index[l2]
		r1 = right_next_index[i]
		r2 = right_next_index[r1]
		ans += p * ((l2 - l1) * (r1 - i) + (r2 - r1) * (i - l2))
		left_next_index[r1] = l2
		right_next_index[l2] = r1
	return ans
n = int(input())
ppp = list(map(int, input().split()))
print(solve(n, ppp))


N = int(input())
P = map(int, input().split())
pos = {}
for (i, p) in enumerate(P):
	pos[p] = i + 1
foll = [i + 1 for i in range(N + 1)] + [N + 1]
prev = [0] + [i for i in range(N + 1)]
ans = 0
for i in range(1, N + 1):
	curr = pos[i]
	r = foll[curr]
	rr = foll[r]
	l = prev[curr]
	ll = prev[l]
	ans += (l - ll) * (r - curr) * i
	ans += (rr - r) * (curr - l) * i
	foll[l] = foll[curr]
	prev[r] = prev[curr]
print(ans)


import sys

def main():
	input = sys.stdin.readline
	N = int(input().strip())
	P = list(map(int, input().strip().split()))
	RR = [i + 1 for i in range(N)]
	LL = [i - 1 for i in range(N)]
	ips = [0] * N
	for (i, val) in enumerate(P):
		ips[val - 1] = i
	P.sort()
	x = 0
	for i in range(N):
		target = ips[P[i] - 1]
		R1ind = RR[target]
		R2ind = RR[min(R1ind, N - 1)]
		L1ind = LL[target]
		L2ind = LL[max(L1ind, 0)]
		x += ((L1ind - L2ind) * (R1ind - target) + (target - L1ind) * (R2ind - R1ind)) * P[i]
		if L1ind != -1:
			RR[L1ind] = R1ind
		if R1ind != N:
			LL[R1ind] = L1ind
	print(x)
main()


def main():
	N = int(input())
	(*p,) = list(map(int, input().split()))
	xtoi = [-1] * (N + 1)
	for (i, x) in enumerate(p):
		xtoi[x] = i
	L = [-1] * (N + 2)
	R = [N] * (N + 2)
	for i in range(N):
		L[i] = i - 1
		R[i] = i + 1
	iter_inds = iter(xtoi)
	next(iter_inds)
	ans = 0
	for (x, ind) in enumerate(iter_inds, start=1):
		l1 = L[ind]
		l2 = L[l1]
		r1 = R[ind]
		r2 = R[r1]
		ans += x * ((l1 - l2) * (r1 - ind) + (r2 - r1) * (ind - l1))
		L[r1] = l1
		R[l1] = r1
	print(ans)

def __starting_point():
	main()
__starting_point()


from bisect import *

class SqrtSet:

	def __init__(self, block_limit=201):
		self.key = []
		self.child = [[]]
		self.block_limit = block_limit

	def le(self, key):
		ret = key
		i = bisect_left(self.key, key)
		if i:
			ret = self.key[i - 1]
		block = self.child[i]
		i = bisect_left(block, key)
		if i:
			ret = block[i - 1]
		return ret

	def ge(self, key):
		ret = key
		i = bisect(self.key, key)
		if i < len(self.key):
			ret = self.key[i]
		block = self.child[i]
		i = bisect(block, key)
		if i < len(block):
			ret = block[i]
		return ret

	def insert(self, key):
		i = bisect(self.key, key)
		block = self.child[i]
		insort(block, key)
		if len(block) == self.block_limit:
			sep = self.block_limit // 2
			self.key.insert(i, block[sep])
			self.child.insert(i + 1, block[sep + 1:])
			self.child[i] = block[:sep]

def main():
	(n, *p) = map(int, open(0).read().split())
	l = [0] * n
	for (i, v) in enumerate(p, 1):
		l[v - 1] = i
	t = SqrtSet()
	(insert, le, ge) = (t.insert, t.le, t.ge)
	(insert(0), insert(n + 1))
	a = 0
	for (i, v) in list(enumerate(l, 1))[::-1]:
		(f, b) = (ge(v), le(v))
		(g, c) = (ge(f), le(b))
		a += i * ((f - v) * (b - c) + (v - b) * (g - f))
		insert(v)
	print(a)
main()


n = int(input())
A = list(map(int, input().split()))
A = [a - 1 for a in A]
P = [-1] * n
for (i, a) in enumerate(A):
	P[a] = i
R = [[n] * 2 for _ in range(n)]
q = []
import heapq
heapq.heapify(q)
for i in range(n):
	temp = []
	while q:
		if q[0][0] < A[i]:
			(v, j) = heapq.heappop(q)
			R[v][j] = i
			if j == 0:
				temp.append((v, j + 1))
		else:
			break
	heapq.heappush(q, (A[i], 0))
	for (v, j) in temp:
		heapq.heappush(q, (v, j))
L = [[-1] * 2 for _ in range(n)]
q = []
import heapq
heapq.heapify(q)
for i in reversed(list(range(n))):
	temp = []
	while q:
		if q[0][0] < A[i]:
			(v, j) = heapq.heappop(q)
			L[v][j] = i
			if j == 0:
				temp.append((v, j + 1))
		else:
			break
	heapq.heappush(q, (A[i], 0))
	for (v, j) in temp:
		heapq.heappush(q, (v, j))
ans = 0
for i in range(n - 1):
	p = P[i]
	l1 = L[i][0]
	l2 = L[i][1]
	r1 = R[i][0]
	r2 = R[i][1]
	ans += ((l1 - l2) * (r1 - p) + (r2 - r1) * (p - l1)) * (i + 1)
print(ans)


class BIT:

	def __init__(self, n):
		self.N = n
		self.n = 1 << n.bit_length()
		self.data = [0] * (self.n + 1)
		self.num = 0

	def sum(self, i):
		s = 0
		while i > 0:
			s += self.data[i]
			i -= i & -i
		return s

	def add(self, i, x):
		while i <= self.n:
			self.data[i] += x
			i += i & -i
		self.num += 1

	def search(self, value):
		if value < 1:
			return 0
		if value > self.num:
			return self.N + 1
		(x, sx) = (0, 0)
		step = self.n
		while step:
			y = x + step
			sy = sx + self.data[y]
			if sy < value:
				(x, sx) = (y, sy)
			step >>= 1
		return x + 1
N = int(input())
P = list(map(int, input().split()))
index = [-1] * N
BIT = BIT(N)
ans = 0
for i in range(N):
	index[P[i] - 1] = i + 1
for (num, p) in enumerate(range(N, 0, -1)):
	i = index[p - 1]
	BIT.add(i, 1)
	j = BIT.sum(i - 1) + 1
	a = BIT.search(j - 2)
	b = BIT.search(j - 1)
	c = BIT.search(j + 1)
	d = BIT.search(j + 2)
	ans += p * ((b - a) * (c - i) + (d - c) * (i - b))
print(ans)


import sys
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines
import bisect

def main():
	(n, *p) = map(int, read().split())
	H = [0, 0, n + 1, n + 1]
	pidx = [0] * (n + 1)
	for i in range(n):
		pidx[p[i]] = i + 1
	pidx.reverse()
	ans = 0
	for i in pidx:
		I = bisect.bisect_left(H, i)
		ans += p[i - 1] * ((H[I - 1] - H[I - 2]) * (H[I] - i) + (H[I + 1] - H[I]) * (i - H[I - 1]))
		H.insert(I, i)
	print(ans)
main()


from sys import stdin
import sys
import numpy as np
import collections
from functools import cmp_to_key
import heapq
sys.setrecursionlimit(100000)

def rsa(sep=''):
	if sep == '':
		return input().split()
	else:
		return input().split(sep)

def rip(sep=''):
	if sep == '':
		return list(map(int, input().split()))
	else:
		return list(map(int, input().split(sep)))

def ria(sep=''):
	return list(rip(sep))

def ri():
	return int(input())

def rd():
	return float(input())

def rs():
	return input()

def main():
	N = ri()
	P = [N + 1, N + 1] + ria() + [N + 1, N + 1]
	ord = []
	for i in range(2, N + 2):
		ord.append((P[i], i))
	ord = sorted(ord)
	tot = 0
	l = [i for i in range(N + 4)]
	r = [i for i in range(N + 4)]
	used = [False] * (N + 4)
	for (v, idx) in ord:
		used[idx] = True
		if used[idx - 1]:
			l[idx] = l[idx - 1]
		if used[idx + 1]:
			r[idx] = r[idx + 1]
		r[l[idx]] = r[idx]
		l[r[idx]] = l[idx]
		l0 = l[idx] - 1
		r0 = r[idx] + 1
		l1 = l0 - 1 if not used[l0 - 1] else l[l0 - 1] - 1
		r1 = r0 + 1 if not used[r0 + 1] else r[r0 + 1] + 1
		if l1 != 0:
			rseg = r0 - idx
			lseg = l0 - l1
			tot += lseg * rseg * v
		if r1 != N + 3:
			rseg = r1 - r0
			lseg = idx - l0
			tot += lseg * rseg * v
	print(tot)

def __starting_point():
	main()
__starting_point()


import sys
readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)

class BinaryIndexTree:

	def __init__(self, n):
		self.size = n
		self._container = [0] * (n + 1)
		self.depth = n.bit_length()

	def sum(self, i):
		if i == 0:
			return 0
		s = 0
		while i > 0:
			s += self._container[i]
			i -= i & -i
		return s

	def add(self, i, x):
		if i == 0:
			return
		while i <= self.size:
			self._container[i] += x
			i += i & -i

	def lower_bound(self, x):
		s = 0
		idx = 0
		for i in range(self.depth, -1, -1):
			k = idx + (1 << i)
			if k <= self.size and s + self._container[k] < x:
				s += self._container[k]
				idx += 1 << i
		return idx + 1

def main():
	n = int(readline())
	p = list(map(int, readline().split()))
	idx = dict()
	for (i, x) in enumerate(p):
		idx[x] = i + 1
	bt = BinaryIndexTree(n + 2)
	bt.add(n + 2, 2)
	bt.add(1, 2)
	ans = 0
	for num in range(n, 0, -1):
		i = idx[num]
		s = bt.sum(i + 1)
		l1 = bt.lower_bound(s)
		l2 = bt.lower_bound(s - 1)
		r1 = bt.lower_bound(s + 1)
		r2 = bt.lower_bound(s + 2)
		ans += num * (i + 1 - l1) * (r2 - r1)
		ans += num * (r1 - i - 1) * (l1 - l2)
		bt.add(i + 1, 1)
	print(ans)
main()


class SegmentTree:

	def __init__(self, array, f, ti):
		self.f = f
		self.ti = ti
		self.n = n = 2 ** len(array).bit_length()
		self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
		for i in range(n - 1, 0, -1):
			dat[i] = f(dat[i << 1], dat[i << 1 | 1])

	def update(self, p, v):
		(f, n, dat) = (self.f, self.n, self.dat)
		p += n
		dat[p] = v
		while p > 1:
			p >>= 1
			dat[p] = f(dat[p << 1], dat[p << 1 | 1])

	def query(self, l, r):
		(f, ti, n, dat) = (self.f, self.ti, self.n, self.dat)
		res = ti
		l += n
		r += n
		while l < r:
			if l & 1:
				res = f(res, dat[l])
				l += 1
			if r & 1:
				r -= 1
				res = f(dat[r], res)
			l >>= 1
			r >>= 1
		return res
N = int(input())
P = [int(_) for _ in input().split()]
p_i = {p: i + 1 for (i, p) in enumerate(P)}
SL = SegmentTree([0] * (N + 2), max, 0)
SR = SegmentTree([N + 1] * (N + 2), min, N + 1)
ans = 0
for p in range(N, 0, -1):
	i = p_i[p]
	SL.update(i, i)
	SR.update(i, i)
	il = SL.query(0, i)
	ir = SR.query(i + 1, N + 2)
	if il > 0:
		ill = SL.query(0, il)
		ans += p * (il - ill) * (ir - i)
	if ir < N + 1:
		irr = SR.query(ir + 1, N + 2)
		ans += p * (irr - ir) * (i - il)
print(ans)


import heapq
from collections import defaultdict
N = int(input())
P = list(map(int, input().split()))
d_r = defaultdict(lambda : N + 1)
h_r = []
d_r2 = defaultdict(lambda : N + 1)
h_r2 = []
for i in range(N):
	p = P[i]
	while h_r2:
		q = heapq.heappop(h_r2)
		if q < p:
			d_r2[q] = p
		else:
			heapq.heappush(h_r2, q)
			break
	while h_r:
		q = heapq.heappop(h_r)
		if q < p:
			d_r[q] = p
			heapq.heappush(h_r2, q)
		else:
			heapq.heappush(h_r, q)
			break
	heapq.heappush(h_r, p)
d_l = defaultdict(lambda : 0)
h_l = []
d_l2 = defaultdict(lambda : 0)
h_l2 = []
for i in range(N - 1, -1, -1):
	p = P[i]
	while h_l2:
		q = heapq.heappop(h_l2)
		if q < p:
			d_l2[q] = p
		else:
			heapq.heappush(h_l2, q)
			break
	while h_l:
		q = heapq.heappop(h_l)
		if q < p:
			d_l[q] = p
			heapq.heappush(h_l2, q)
		else:
			heapq.heappush(h_l, q)
			break
	heapq.heappush(h_l, p)
d = {}
for i in range(N):
	d[P[i]] = i
d[N + 1] = N
d[0] = -1
ans = 0
for i in range(N):
	x = d[d_l2[P[i]]]
	y = d[d_l[P[i]]]
	z = d[d_r[P[i]]]
	w = d[d_r2[P[i]]]
	ans += P[i] * ((y - x) * (z - i) + (w - z) * (i - y))
print(ans)


N = int(input())
P = [None] + list(map(int, input().split()))
p_to_index = [None] * (N + 1)
for (index, x) in enumerate(P[1:], 1):
	p_to_index[x] = index

def BIT_add(i):
	while i <= N:
		tree[i] += 1
		i += i & -i

def BIT_sum(i):
	s = 0
	while i:
		s += tree[i]
		i -= i & -i
	return s

def BIT_search(x):
	i = 0
	s = 0
	step = 1 << N.bit_length() - 1
	while step:
		if i + step <= N and s + tree[i + step] < x:
			i += step
			s += tree[i]
		step >>= 1
	return i + 1
tree = [0] * (N + 1)
ans = 0
for x in range(N, 0, -1):
	c = p_to_index[x]
	L = BIT_sum(c)
	BIT_add(c)
	R = N - x - L
	a = BIT_search(L - 1) if L >= 2 else 0
	b = BIT_search(L) if L >= 1 else 0
	d = BIT_search(L + 2) if R >= 1 else N + 1
	e = BIT_search(L + 3) if R >= 2 else N + 1
	tmp = 0
	if b != 0:
		tmp += (b - a) * (d - c)
	if d != 0:
		tmp += (e - d) * (c - b)
	ans += tmp * x
print(ans)


n = int(input())
lst = list(enumerate(list(map(int, input().split()))))
sorted_lst = sorted(lst, key=lambda x: x[1])
left_next_index = list(range(-1, n - 1)) + [-1, -1]
right_next_index = list(range(1, n + 1)) + [n, n]
ans = 0
for (i, p) in sorted_lst:
	l2 = left_next_index[i]
	l1 = left_next_index[l2]
	r1 = right_next_index[i]
	r2 = right_next_index[r1]
	a = p * ((l2 - l1) * (r1 - i) + (r2 - r1) * (i - l2))
	ans += a
	left_next_index[r1] = l2
	right_next_index[l2] = r1
print(ans)


class Bit:

	def __init__(self, n):
		self.size = n
		self.tree = [0] * (n + 1)
		self.depth = n.bit_length()

	def sum(self, i):
		s = 0
		while i > 0:
			s += self.tree[i]
			i -= i & -i
		return s

	def add(self, i, x):
		while i <= self.size:
			self.tree[i] += x
			i += i & -i

	def lower_bound(self, x):
		sum_ = 0
		pos = 0
		for i in range(self.depth, -1, -1):
			k = pos + (1 << i)
			if k <= self.size and sum_ + self.tree[k] < x:
				sum_ += self.tree[k]
				pos += 1 << i
		return (pos + 1, sum_)

	def get_less_than_x_cnt(self, x):
		(lb_pos, lb_sum) = self.lower_bound(x)
		return lb_pos - 1

	def get_less_than_and_x_cnt(self, x):
		(lb_pos, lb_sum) = self.lower_bound(x + 1)
		return lb_pos - 1

	def get_more_than_x_cnt(self, x):
		return self.size - self.get_less_than_and_x_cnt(x)
n = int(input())
pl = list(map(int, input().split()))
pll = []
for (i, p) in enumerate(pl):
	pll.append((p, i + 2))
pll.sort(reverse=True)
bit = Bit(n + 1)
bit.add(1, 1)
ans = 0
for (p, i) in pll:
	ix = bit.sum(i)
	(lmax, _) = bit.lower_bound(ix)
	(lmin, _) = bit.lower_bound(ix - 1)
	lcnt = lmax - lmin
	(rmin, _) = bit.lower_bound(ix + 1)
	(rmax, _) = bit.lower_bound(ix + 2)
	rcnt = rmax - rmin
	comb = lcnt * (rmin - i) + (i - lmax) * rcnt
	ans += comb * p
	bit.add(i, 1)
print(ans)


def main():
	n = int(input())
	xx = list(map(int, input().split()))
	pp = [(xx[i], i + 1) for i in range(n)]
	pp.sort(key=lambda x: x[0])
	left = [0, 0] + [i + 1 for i in range(n)]
	right = [i + 1 for i in range(n)] + [n + 1, n + 1]
	ans = 0
	for i in range(n):
		(ori_num, ori_ind) = pp[i]
		l1 = left[ori_ind]
		l2 = left[l1]
		r1 = right[ori_ind]
		r2 = right[r1]
		ans += ((l1 - l2) * (r1 - ori_ind) + (ori_ind - l1) * (r2 - r1)) * ori_num
		right[l1] = r1
		left[r1] = l1
	print(ans)
main()


import bisect

class BTreeNode:

	def __init__(self):
		self.key = []
		self.child = []

class BTree:

	def __init__(self):
		self.root = BTreeNode()

	def search_higher(self, key):
		ptr = self.root
		ret = None
		while ptr.child:
			i = bisect.bisect_right(ptr.key, key)
			if i != len(ptr.key):
				ret = ptr.key[i]
			ptr = ptr.child[i]
		i = bisect.bisect_right(ptr.key, key)
		if i != len(ptr.key):
			ret = ptr.key[i]
		return ret

	def search_lower(self, key):
		ptr = self.root
		ret = None
		while ptr.child:
			i = bisect.bisect_left(ptr.key, key)
			if i != 0:
				ret = ptr.key[i - 1]
			ptr = ptr.child[i]
		i = bisect.bisect_left(ptr.key, key)
		if i != 0:
			ret = ptr.key[i - 1]
		return ret

	def insert(self, key):

		def insert_rec(ptr):
			b_size = 512
			if not ptr.child:
				bisect.insort(ptr.key, key)
				if len(ptr.key) == b_size * 2 - 1:
					ret = BTreeNode()
					ret.key = ptr.key[:b_size]
					ptr.key = ptr.key[b_size:]
					return ret
			else:
				i = bisect.bisect(ptr.key, key)
				temp = insert_rec(ptr.child[i])
				if temp is not None:
					ptr.key.insert(i, temp.key.pop(-1))
					ptr.child.insert(i, temp)
					if len(ptr.child) == b_size * 2:
						ret = BTreeNode()
						ret.child = ptr.child[:b_size]
						ptr.child = ptr.child[b_size:]
						ret.key = ptr.key[:b_size]
						ptr.key = ptr.key[b_size:]
						return ret
			return None
		temp = insert_rec(self.root)
		if temp is not None:
			root = BTreeNode()
			root.key = [temp.key.pop(-1)]
			root.child = [temp, self.root]
			self.root = root

	def dump(self):

		def dump_rec(ptr, dep):
			for _ in range(0, dep):
				print('  ', end='')
			print(ptr.key)
			for c in ptr.child:
				dump_rec(c, dep + 1)
		dump_rec(self.root, 0)
		print('')

def main():
	n = int(input())
	p = list(map(int, input().split()))
	idx = [0] * n
	for i in range(0, n):
		idx[i] = i
	idx.sort(key=lambda i: -p[i])
	t = BTree()
	t.insert(-1)
	t.insert(n)
	ans = 0
	for i in idx:
		nex = t.search_higher(i)
		nexnex = t.search_higher(nex)
		pre = t.search_lower(i)
		prepre = t.search_lower(pre)
		if prepre != None:
			ans += p[i] * (pre - prepre) * (nex - i)
		if nexnex != None:
			ans += p[i] * (i - pre) * (nexnex - nex)
		t.insert(i)
	print(ans)
main()


class BIT:

	def __init__(self, n):
		self.n = n
		self.N = 1 << n.bit_length()
		self.data = [0] * (self.N + 1)

	def add(self, i, x):
		while i <= self.N:
			self.data[i] += x
			i += i & -i

	def sum(self, i):
		total = 0
		while i > 0:
			total += self.data[i]
			i -= i & -i
		return total

	def search(self, w):
		if w <= 0:
			return 0
		x = 0
		k = self.N >> 1
		while k > 0:
			if x + k <= self.N and self.data[x + k] < w:
				w -= self.data[x + k]
				x += k
			k = k >> 1
		return x + 1

	def len(self):
		return self.data[self.N]
n = int(input())
p = list(map(int, input().split()))
index = [0] * (n + 1)
for i in range(n):
	index[p[i]] = i + 1
used = BIT(n)
result = 0
for i in range(1, n + 1)[::-1]:
	x = index[i]
	if used.len() == 0:
		used.add(x, 1)
		continue
	dx = used.sum(x)
	if dx > 0:
		lbl = 1
		if dx > 1:
			lbl = used.search(dx - 1) + 1
		lbr = used.search(dx)
		rbl = n
		if used.len() != dx:
			rbl = used.search(dx + 1) - 1
		result += (lbr - lbl + 1) * (rbl - x + 1) * i
	if dx < used.len():
		rbr = n
		if dx < used.len() - 1:
			rbr = used.search(dx + 2) - 1
		rbl = used.search(dx + 1)
		lbr = 1
		if dx > 0:
			lbr = used.search(dx) + 1
		result += (rbr - rbl + 1) * (x - lbr + 1) * i
	used.add(x, 1)
print(result)


n = int(input())
P = [int(i) for i in input().split()]
n_max = 10 ** 5
nn = n_max.bit_length() + 1
BIT = [0] * 2 ** nn
BIT.insert(0, 0)

def bitsum(BIT, i):
	s = 0
	while i > 0:
		s += BIT[i]
		i -= i & -i
	return s

def bitadd(BIT, i, x):
	while i <= 2 ** nn:
		BIT[i] += x
		i += i & -i
	return BIT

def bitlb(BIT, s):
	if s <= 0:
		return 0
	else:
		ret = 0
		k = 2 ** nn
		while k > 0:
			if k + ret <= 2 ** nn and BIT[k + ret] < s:
				s -= BIT[k + ret]
				ret += k
			k //= 2
		return ret + 1
D = dict()
for i in range(n):
	D[P[i]] = i + 1
PP = sorted(P, reverse=True)
bitadd(BIT, D[PP[0]], 1)
ans = 0
for i in range(1, n):
	cur = D[PP[i]]
	bitadd(BIT, cur, 1)
	tot = bitsum(BIT, cur)
	(l2, l1, r1, r2) = (bitlb(BIT, tot - 2), bitlb(BIT, tot - 1), min(n + 1, bitlb(BIT, tot + 1)), min(n + 1, bitlb(BIT, tot + 2)))
	add = PP[i] * ((-l1 + cur) * (r2 - r1) + (l1 - l2) * (r1 - cur))
	ans += add
print(ans)


import sys, bisect as bs, collections as cl
sys.setrecursionlimit(100000)
mod = 10 ** 9 + 7
Max = sys.maxsize

def l():
	return list(map(int, input().split()))

def m():
	return map(int, input().split())

def onem():
	return int(input())

def s(x):
	a = []
	aa = x[0]
	su = 1
	for i in range(len(x) - 1):
		if aa != x[i + 1]:
			a.append([aa, su])
			aa = x[i + 1]
			su = 1
		else:
			su += 1
	a.append([aa, su])
	return a

def jo(x):
	return ' '.join(map(str, x))

def max2(x):
	return max(map(max, x))

def In(x, a):
	k = bs.bisect_left(a, x)
	if k != len(a) and a[k] == x:
		return True
	else:
		return False
n = onem()
p = [0] + l() + [n + 1]
ans = 0
a = [0 for i in range(n + 2)]
for i in range(n + 2):
	a[p[i]] = i
l = [set() for i in range(n + 2)]
r = [set() for i in range(n + 2)]
for i in range(n + 2):
	l[i].add(max(0, i - 1))
	l[i].add(max(0, i - 2))
	r[i].add(min(n + 1, i + 1))
	r[i].add(min(n + 1, i + 2))
for i in range(n + 1):
	m = a[i]
	(x2, x1, y1, y2) = (min(l[m]), max(l[m]), min(r[m]), max(r[m]))
	hoge = i * (abs((m - x1) * (y2 - y1)) + abs((y1 - m) * (x1 - x2)))
	ans += hoge
	r[x1].clear()
	r[x1].add(y1)
	r[x1].add(y2)
	l[y1].clear()
	l[y1].add(x1)
	l[y1].add(x2)
	r[x2].clear()
	r[x2].add(x1)
	r[x2].add(y1)
	l[y2].clear()
	l[y2].add(y1)
	l[y2].add(x1)
print(ans)


n = int(input())
p = list(map(int, input().split()))
p_ind = [(p[i], i + 1) for i in range(n)]
p_ind.sort(reverse=True)
max_n = 10 ** 5
div_n = int(max_n ** (1 / 2)) + 1
a = [[] for _ in range(div_n)]
a[0] = [0, 0]
a[(n + 1) // div_n].append(n + 1)
a[(n + 1) // div_n].append(n + 1)
a_count = [0] * div_n
a_count[0] += 2
a_count[(n + 1) // div_n] += 2
import bisect
ans = 0
for tmp in p_ind:
	(val, i) = tmp
	group = i // div_n
	j = bisect.bisect(a[group], i)
	if j > 1:
		left1 = a[group][j - 1]
		left2 = a[group][j - 2]
	elif j == 1:
		left1 = a[group][j - 1]
		lg = group - 1
		while True:
			if a_count[lg] > 0:
				break
			lg -= 1
		left2 = a[lg][-1]
	else:
		lg = group - 1
		while True:
			if a_count[lg] > 0:
				break
			lg -= 1
		if a_count[lg] >= 2:
			left1 = a[lg][-1]
			left2 = a[lg][-2]
		else:
			left1 = a[lg][-1]
			while True:
				lg -= 1
				if a_count[lg] > 0:
					break
			left2 = a[lg][-1]
	if a_count[group] >= j + 2:
		right1 = a[group][j]
		right2 = a[group][j + 1]
	elif a_count[group] >= j + 1:
		right1 = a[group][j]
		rg = group
		while True:
			rg += 1
			if a_count[rg] > 0:
				break
		right2 = a[rg][0]
	else:
		rg = group
		while True:
			rg += 1
			if a_count[rg] > 0:
				break
		if a_count[rg] >= 2:
			right1 = a[rg][0]
			right2 = a[rg][1]
		else:
			right1 = a[rg][0]
			while True:
				rg += 1
				if a_count[rg] > 0:
					break
			right2 = a[rg][0]
	ans += ((right2 - right1) * (i - left1) + (right1 - i) * (left1 - left2)) * val
	a[group].insert(j, i)
	a_count[group] += 1
print(ans)


N = int(input())
Pn = list(map(int, input().split()))
In = [0] * (N + 1)
for i in range(N):
	In[Pn[i]] = i + 1
cnt = 0
l = [0] + [i for i in range(N + 1)]
r = [i + 1 for i in range(N + 1)] + [N + 1]
for v in range(1, N + 1):
	i = In[v]
	l1 = l[i]
	l2 = l[l1]
	r1 = r[i]
	r2 = r[r1]
	cnt += ((l1 - l2) * (r1 - i) + (i - l1) * (r2 - r1)) * v
	l[r1] = l1
	r[l1] = r1
print(cnt)


import bisect
N = int(input())
P = list(map(int, input().split()))
pos = [-1] * (N + 1)
for i in range(N):
	pos[P[i]] = i
called = [-1, -1, pos[N], N, N]
ans = 0
for i in range(N - 1, 0, -1):
	hoge = pos[i]
	r = bisect.bisect_left(called, hoge)
	R = called[r]
	RR = called[r + 1]
	L = called[r - 1]
	LL = called[r - 2]
	ans += i * ((RR - R) * (hoge - L) + (L - LL) * (R - hoge))
	called.insert(r, hoge)
print(ans)


N = int(input())
P = list(map(int, input().split()))
I = [0] * N
for i in range(N):
	I[P[i] - 1] = i
ans = 0
L = [i for i in range(-1, N - 1)]
R = [i for i in range(1, N + 1)]
for p in range(1, N + 1):
	i = I[p - 1]
	if R[i] < N:
		L[R[i]] = L[i]
	if L[i] >= 0:
		R[L[i]] = R[i]
	l1 = L[i]
	l2 = L[l1] if l1 >= 0 else -1
	r1 = R[i]
	r2 = R[r1] if r1 < N else N
	ans += p * ((r1 - i) * (l1 - l2) + (i - l1) * (r2 - r1))
print(ans)


import heapq
N = int(input())
P = list(map(int, input().split()))
Llis = []
Rlis = []
for i in range(N):
	Llis.append([N, N])
	Rlis.append([N, N])
	P[i] -= 1
LQ1 = []
LQ2 = []
for i in range(N):
	while len(LQ2) > 0 and LQ2[0][0] < P[i]:
		Llis[LQ2[0][1]][1] = i
		heapq.heappop(LQ2)
	while len(LQ1) > 0 and LQ1[0][0] < P[i]:
		Llis[LQ1[0][1]][0] = i
		heapq.heappush(LQ2, LQ1[0])
		heapq.heappop(LQ1)
	heapq.heappush(LQ1, [P[i], i])
P.reverse()
LQ1 = []
LQ2 = []
for i in range(N):
	while len(LQ2) > 0 and LQ2[0][0] < P[i]:
		Rlis[LQ2[0][1]][1] = i
		heapq.heappop(LQ2)
	while len(LQ1) > 0 and LQ1[0][0] < P[i]:
		Rlis[LQ1[0][1]][0] = i
		heapq.heappush(LQ2, LQ1[0])
		heapq.heappop(LQ1)
	heapq.heappush(LQ1, [P[i], i])
Rlis.reverse()
ans = 0
P.reverse()
for i in range(N):
	Llenge = Llis[i][1] - Llis[i][0]
	Rlenge = 1 + max(0, i - (N - Rlis[i][0]))
	ans += (P[i] + 1) * Llenge * Rlenge
P.reverse()
Rlis.reverse()
Llis.reverse()
for i in range(N):
	Rlenge = Rlis[i][1] - Rlis[i][0]
	Llenge = 1 + max(0, i - (N - Llis[i][0]))
	ans += (P[i] + 1) * Llenge * Rlenge
print(ans)


import math
import os
import sys
DEBUG = 'DEBUG' in os.environ

def inp():
	return sys.stdin.readline().rstrip()

def dprint(*value, sep=' ', end='\n'):
	if DEBUG:
		print(*value, sep=sep, end=end)

def solve(N, P):
	revp = [-1] * (N + 1)
	for (i, p) in enumerate(P):
		revp[p] = i
	segt = [[(v, 0) for v in P]]
	while len(segt[-1]) > 1:
		base = segt[-1]
		if len(base) % 2 == 1:
			base.append((0, 0))
		new = []
		for i in range(len(base) // 2):
			(a, b) = base[2 * i]
			(c, d) = base[2 * i + 1]
			arr = [a, b, c, d]
			arr.sort()
			new.append((arr[-1], arr[-2]))
		segt.append(new)
	dprint('segt', segt)

	def get12(i, j):
		if j - i <= 0:
			return (0, 0)
		segi = 0
		top = []
		while True:
			if j - i <= 0:
				break
			seg = segt[segi]
			if j - i == 1:
				top.extend(seg[i])
				break
			if i % 2 == 1:
				top.extend(seg[i])
				i += 1
			if j % 2 == 1:
				top.extend(seg[j - 1])
				j -= 1
			i //= 2
			j //= 2
			segi += 1
		top.sort()
		return (top[-1], top[-2])
	cache = [dict() for _ in range(N)]
	stk = [(0, N)]
	while stk:
		item = stk.pop()
		if len(item) == 2:
			(i, j) = item
			if j in cache[i]:
				continue
			(a, b) = get12(i, j)
			ai = revp[a]
			bi = revp[b]
			(li, ri) = (ai, bi) if ai < bi else (bi, ai)
			ri += 1
			sc = b * (li - i + 1) * (j - ri + 1)
			want = [(i, ri - 1), (li + 1, j), (li + 1, ri - 1)]
			req = []
			for (c, d) in want:
				if not (d - c < 2 or d in cache[c]):
					req.append((c, d))
			if not req:
				(left, right, mid) = [0 if d - c < 2 else cache[c][d] for (c, d) in want]
				cache[i][j] = left + right - mid + sc
				continue
			stk.append((i, j, want, sc))
			for r in req:
				stk.append(r)
			continue
		(i, j, want, sc) = item
		(left, right, mid) = [0 if d - c < 2 else cache[c][d] for (c, d) in want]
		cache[i][j] = left + right - mid + sc
	return cache[0][N]

def main():
	N = int(inp())
	P = [int(e) for e in inp().split()]
	print(solve(N, P))
main()


class SegmentTree:

	def __init__(self, A, dot, e):
		n = 2 ** (len(A) - 1).bit_length()
		self.__n = n
		self.__dot = dot
		self.__e = e
		self.__node = [e] * (2 * n)

	def update(self, i, c):
		i += self.__n
		node = self.__node
		node[i] = c
		while i > 0:
			i //= 2
			node[i] = self.__dot(node[2 * i], node[2 * i + 1])

	def get(self, l, r):
		(vl, vr) = (self.__e, self.__e)
		l += self.__n
		r += self.__n
		while l < r:
			if l & 1:
				vl = self.__dot(vl, self.__node[l])
				l += 1
			l //= 2
			if r & 1:
				r -= 1
				vr = self.__dot(vr, self.__node[r])
			r //= 2
		return self.__dot(vl, vr)

def solve():
	N = int(input())
	P = map(int, input().split())
	plist = []
	for (i, p) in enumerate(P):
		plist.append((p, i))
	plist.sort(reverse=True)
	maxSeg = SegmentTree([-1] * N, max, -1)
	minSeg = SegmentTree([N] * N, min, N)
	cnt = 0
	for (p, c) in plist:
		l2 = maxSeg.get(0, c)
		l1 = -1 if l2 <= 0 else maxSeg.get(0, l2)
		r1 = minSeg.get(c + 1, N)
		r2 = N if r1 >= N - 1 else minSeg.get(r1 + 1, N)
		a = (l2 - l1) * (r1 - c)
		b = (r2 - r1) * (c - l2)
		cnt += p * (a + b)
		maxSeg.update(c, c)
		minSeg.update(c, c)
	print(cnt)
solve()


class BIT1:

	def __init__(self, n):
		self.n = n
		self.bit = [0] * (self.n + 1)
		self.data = [0] * (self.n + 1)

	def build(self, data):
		pass

	def add(self, idx, x):
		self.data[idx] += x
		while idx <= self.n:
			self.bit[idx] += x
			idx += idx & -idx

	def sum(self, idx):
		s = 0
		while idx:
			s += self.bit[idx]
			idx -= idx & -idx
		return s

	def bisect_left(self, w):
		if w <= 0:
			return 0
		idx = 0
		k = 1 << self.n.bit_length() - 1
		while k > 0:
			if idx + k <= self.n and self.bit[idx + k] < w:
				w -= self.bit[idx + k]
				idx += k
			k = k >> 1
		return idx + 1

	def bisect_right(self, w):
		if w < 0:
			return 0
		idx = 0
		k = 1 << self.n.bit_length() - 1
		while k > 0:
			if idx + k <= self.n and self.bit[idx + k] <= w:
				w -= self.bit[idx + k]
				idx += k
			k = k >> 1
		return idx + 1
n = int(input())
p = [0] + list(map(int, input().split()))
p2idx = [0] * (n + 1)
for i in range(1, n + 1):
	p2idx[p[i]] = i
ans = 0
bit = BIT1(n)
for x in reversed(range(1, n + 1)):
	idx = p2idx[x]
	bit.add(idx, 1)
	idx_rank = bit.sum(idx)
	idx_l2 = bit.bisect_left(idx_rank - 2)
	idx_l1 = bit.bisect_left(idx_rank - 1)
	idx_r1 = bit.bisect_left(idx_rank + 1)
	idx_r2 = bit.bisect_left(idx_rank + 2)
	cnt = 0
	cnt += (idx_l1 - idx_l2) * (idx_r1 - idx)
	cnt += (idx - idx_l1) * (idx_r2 - idx_r1)
	ans += x * cnt
print(ans)


n = int(input())
p = list(map(int, input().split()))

def get_de(p):
	(d, e) = ([n for i in range(n)], [n for i in range(n)])
	stack1 = []
	stack2 = []
	for i in range(n):
		while stack2 and p[stack2[-1]] < p[i]:
			idx = stack2.pop()
			e[idx] = i
		to_append = []
		while stack1 and p[stack1[-1]] < p[i]:
			idx = stack1.pop()
			d[idx] = i
			to_append.append(idx)
		while to_append:
			stack2.append(to_append.pop())
		stack1.append(i)
	(dist1, dist2) = ([], [])
	for i in range(n):
		dist1.append(d[i] - i)
		dist2.append(e[i] - d[i])
	return (dist1, dist2)
(dist1, dist2) = get_de(p)
(dist3, dist4) = get_de(p[::-1])
(dist3, dist4) = (dist3[::-1], dist4[::-1])
ans = 0
for i in range(n):
	ans += (dist1[i] * dist4[i] + dist2[i] * dist3[i]) * p[i]
print(ans)


from bisect import bisect_left, bisect_right, insort_right

class SquareSkipList:

	def __init__(self, values=None, sorted_=False, square=1000, seed=42):
		inf = float('inf')
		self.rand_y = seed
		self.square = square
		if values is None:
			self.layer1 = []
			self.layer0 = [[]]
		else:
			self.layer1 = layer1 = []
			self.layer0 = layer0 = []
			if not sorted_:
				values.sort()
			rand_depth = self.rand_depth
			l0 = []
			for v in values:
				if rand_depth():
					layer0.append(l0)
					l0 = []
					layer1.append(v)
				else:
					l0.append(v)
			layer0.append(l0)
		self.layer1.append(inf)

	def rand_depth(self):
		y = self.rand_y
		y ^= y << 13 & 4294967295
		y ^= y >> 17
		y ^= y << 5 & 4294967295
		self.rand_y = y
		return y % self.square == 0

	def add(self, x):
		(layer1, layer0) = (self.layer1, self.layer0)
		if self.rand_depth():
			idx1 = bisect_right(layer1, x)
			layer1.insert(idx1, x)
			layer0_idx1 = layer0[idx1]
			idx0 = bisect_right(layer0_idx1, x)
			layer0.insert(idx1 + 1, layer0_idx1[idx0:])
			del layer0_idx1[idx0:]
		else:
			idx1 = bisect_right(layer1, x)
			insort_right(layer0[idx1], x)

	def remove(self, x):
		(layer1, layer0) = (self.layer1, self.layer0)
		idx1 = bisect_left(layer1, x)
		if layer1[idx1] == x:
			del layer1[idx1]
			layer0[idx1] += layer0[idx1 + 1]
			del layer0[idx1 + 1]
		else:
			layer0_idx1 = layer0[idx1]
			del layer0_idx1[bisect_left(layer0_idx1, x)]

	def bisect_left(self, x):
		(layer1, layer0) = (self.layer1, self.layer0)
		idx1 = bisect_left(layer1, x)
		res = layer1[idx1]
		if res == x:
			return res
		layer0_idx1 = layer0[idx1]
		if layer0_idx1:
			idx0 = bisect_left(layer0_idx1, x)
			if idx0 == len(layer0_idx1):
				return res
			else:
				return layer0_idx1[idx0]
		else:
			return res

	def search_higher(self, x):
		(layer1, layer0) = (self.layer1, self.layer0)
		idx1 = bisect_right(layer1, x)
		res = layer1[idx1]
		layer0_idx1 = layer0[idx1]
		if layer0_idx1:
			idx0 = bisect_right(layer0_idx1, x)
			if idx0 == len(layer0_idx1):
				return res
			else:
				return layer0_idx1[idx0]
		else:
			return res

	def search_lower(self, x):
		(layer1, layer0) = (self.layer1, self.layer0)
		idx1 = bisect_left(layer1, x)
		res = layer1[idx1]
		layer0_idx1 = layer0[idx1]
		if res != x:
			if layer0_idx1:
				idx0 = bisect_left(layer0_idx1, x)
				if idx0 != 0:
					return layer0_idx1[idx0 - 1]
			return layer1[idx1 - 1]
		else:
			idx0 = bisect_left(layer0_idx1, x)
			if idx0 == 0:
				return layer1[idx1 - 1]
			else:
				return layer0_idx1[idx0 - 1]

	def pop(self, idx):
		(layer1, layer0) = (self.layer1, self.layer0)
		s = -1
		for (i, l0) in enumerate(layer0):
			s += len(l0) + 1
			if s >= idx:
				break
		if s == idx:
			layer0[i] += layer0[i + 1]
			del layer0[i + 1]
			return layer1.pop(i)
		else:
			return layer0[i].pop(idx - s)
N = int(input())
P = list(map(int, input().split()))
D = {P[i]: i + 1 for i in range(N)}
ans = 0
L = SquareSkipList()
L.add(D[N])
for i in range(1, N)[::-1]:
	l = L.search_lower(D[i])
	h = L.search_higher(D[i])
	if l == float('inf'):
		hh = L.search_higher(h)
		if hh == float('inf'):
			hh = N + 1
		ans += D[i] * (hh - h) * i
	elif h == float('inf'):
		ll = L.search_lower(l)
		if ll == float('inf'):
			ll = 0
		ans += (N + 1 - D[i]) * (l - ll) * i
	else:
		hh = L.search_higher(h)
		if hh == float('inf'):
			hh = N + 1
		ll = L.search_lower(l)
		if ll == float('inf'):
			ll = 0
		ans += ((h - D[i]) * (l - ll) + (D[i] - l) * (hh - h)) * i
	L.add(D[i])
print(ans)


import bisect
import array
N = int(input())
P = list(map(int, input().split()))
P_id = [0] * (N + 1)
for i in range(N):
	P_id[P[i]] = i
A = array.array('i', [-1, P_id[N], N])
res = 0
for i in range(N - 1, 0, -1):
	j = bisect.bisect_left(A, P_id[i])
	A.insert(j, P_id[i])
	l1 = A[j - 1]
	r1 = A[j + 1]
	l2 = l1
	r2 = r1
	if l1 != -1:
		l2 = A[j - 2]
	if r1 != N:
		r2 = A[j + 2]
	res += i * ((A[j] - l1) * (r2 - r1) + (l1 - l2) * (r1 - A[j]))
print(res)


n = int(input())
P = list(map(int, input().split()))
num_idx = [0] * (n + 1)
right_idx_over_current_pos = list(range(1, n + 1)) + [n, n]
left_idx_over_current_pos = list(range(-1, n - 1)) + [-1, -1]
for (idx, num) in enumerate(P):
	num_idx[num] = idx
ans = 0
for num in range(1, n + 1):
	now = num_idx[num]
	r1 = right_idx_over_current_pos[now]
	r2 = right_idx_over_current_pos[r1]
	l1 = left_idx_over_current_pos[now]
	l2 = left_idx_over_current_pos[l1]
	r_pattern = (r2 - r1) * (now - l1)
	l_pattern = (l1 - l2) * (r1 - now)
	right_idx_over_current_pos[l1] = r1
	left_idx_over_current_pos[r1] = l1
	ans += (r_pattern + l_pattern) * num
print(ans)


N = int(input())
P = [int(x) for x in input().split()]
PIdx = sorted([(i + 1, v) for (i, v) in enumerate(P)], key=lambda x: x[1])
L = [0]
for i in range(N + 1):
	L.append(i)
R = [i + 1 for i in range(N + 1)]
R.append(N + 1)
ans = 0
for (i, v) in PIdx:
	l1 = L[i]
	l2 = L[l1]
	r1 = R[i]
	r2 = R[r1]
	ans += v * ((i - l1) * (r2 - r1) + (l1 - l2) * (r1 - i))
	L[r1] = l1
	R[l1] = r1
print(ans)


def f_e():
	(n, *p) = list(map(int, open(0).read().split()))
	p = sorted([(v, i) for (i, v) in enumerate(p)])
	(*l,) = list(range(-1, n - 1))
	(*r,) = list(range(1, n + 1))
	a = 0
	for (v, i) in p:
		(l0, r0) = (l[i], r[i])
		l1 = l[l0] if l0 > -1 else l0
		r1 = r[r0] if r0 < n else r0
		a += ((l0 - l1) * (r0 - i) + (r1 - r0) * (i - l0)) * v
		if l0 > -1:
			r[l0] = r0
		if r0 < n:
			l[r0] = l0
	print(a)

def __starting_point():
	f_e()
__starting_point()


import bisect

def find_left(P, position):
	N = len(P)
	left1 = [-1] * N
	left2 = [-1] * N
	stack = []
	popped = [[] for i in range(len(P))]
	stack = [P[0]]
	for i in range(1, len(P)):
		while stack:
			if stack[-1] < P[i]:
				popped[i] += [stack.pop()]
			else:
				left1[i] = stack[-1]
				stack += [P[i]]
				break
		if stack == []:
			stack += [P[i]]
			left1[i] = -1
		if left1[i] == -1:
			left2[i] == -1
		else:
			val = left1[i]
			pos = position[val]
			big_val_pos = len(popped[pos])
			if popped[pos]:
				big_val_pos = bisect.bisect_left(popped[pos], P[i])
				if big_val_pos < len(popped[pos]):
					left2[i] = popped[pos][big_val_pos]
			if left2[i] == -1:
				if len(stack) >= 3:
					left2[i] = stack[-3]
	return (left1, left2)

def find_right(P, position):
	position = [len(P) - x - 1 for x in position]
	(right1, right2) = find_left(P[::-1], position)
	return (right1[::-1], right2[::-1])
input()
P = list(map(int, input().strip().split(' ')))
N = len(P)
P = [p - 1 for p in P]
position = [0] * len(P)
for i in range(len(P)):
	position[P[i]] = i
(left1, left2) = find_left(P, position)
(right1, right2) = find_right(P, position)
for i in range(N):
	if left1[i] != -1:
		left1[i] = position[left1[i]]
	if left2[i] != -1:
		left2[i] = position[left2[i]]
	if right1[i] == -1:
		right1[i] = N
	else:
		right1[i] = position[right1[i]]
	if right2[i] == -1:
		right2[i] = N
	else:
		right2[i] = position[right2[i]]
ans = 0
for i in range(N):
	(L1, L2, R1, R2) = (left1[i], left2[i], right1[i], right2[i])
	val = P[i] + 1
	if val == N:
		continue
	temp = 0
	if L1 == -1:
		temp += (i + 1) * (R2 - R1)
	elif R1 == N:
		temp += (L1 - L2) * (N - i)
	else:
		temp += (L1 - L2) * (R1 - i)
		temp += (i - L1) * (R2 - R1)
	ans += temp * val
print(ans)


from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools
import queue
from collections import deque

def main():
	num = int(input())
	data = list(map(int, input().split()))
	for i in range(num):
		data[i] = (data[i], i + 1)
	data.sort(key=lambda x: x[0])
	left = [0, 0] + [i + 1 for i in range(num)]
	right = [i + 1 for i in range(num)] + [num + 1, num + 1]
	ans = 0
	for i in range(num):
		(ori_num, ori_ind) = data[i]
		l1 = left[ori_ind]
		l2 = left[l1]
		r1 = right[ori_ind]
		r2 = right[r1]
		ans += ((l1 - l2) * (r1 - ori_ind) + (ori_ind - l1) * (r2 - r1)) * ori_num
		right[l1] = r1
		left[r1] = l1
	print(ans)
main()


import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop, heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10 ** 9 + 7
inf = float('inf')

def I():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))
n = I()
p = LI()
f = [0] * (n + 1)
for i in range(n):
	f[p[i]] = i + 1
ans = 0
l = [0] + [i for i in range(n + 1)]
r = [i + 1 for i in range(n + 1)] + [n + 1]
for i in range(1, n + 1):
	x = f[i]
	(l1, r1) = (l[x], r[x])
	(l2, r2) = (l[l1], r[r1])
	ans += ((l1 - l2) * (r1 - x) + (x - l1) * (r2 - r1)) * i
	(l[r1], r[l1]) = (l1, r1)
print(ans)


import sys
stdin = sys.stdin
ni = lambda : int(ns())
na = lambda : list(map(int, stdin.readline().split()))
ns = lambda : stdin.readline().rstrip()
n = ni()
a = na()
st = []
ans = 0
gans = 0
for i in range(n):
	v = a[i]
	l = 0
	bst = []
	while len(st) > 0 and st[-1][1] < v:
		h = st.pop(-1)
		ans -= h[1] * h[2]
		if h[0] < v:
			(h[0], h[1]) = (v, h[0])
		else:
			h[1] = v
		ans += h[1] * h[2]
		if len(bst) > 0 and bst[-1][0] == h[0] and (bst[-1][1] == h[1]):
			bst[-1][2] += h[2]
		else:
			bst.append(h)
	st.extend(bst[::-1])
	st.append([v, 0, 1])
	gans += ans
print(gans)


import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from operator import itemgetter
n = int(readline())
ppp = list(map(int, readline().split()))

class Bit:

	def __init__(self, n):
		self.size = n
		self.tree = [0] * (n + 1)
		self.depth = n.bit_length()

	def sum(self, i):
		s = 0
		while i > 0:
			s += self.tree[i]
			i -= i & -i
		return s

	def add(self, i, x):
		while i <= self.size:
			self.tree[i] += x
			i += i & -i

	def lower_bound(self, x):
		sum_ = 0
		pos = 0
		for i in range(self.depth, -1, -1):
			k = pos + (1 << i)
			if k <= self.size and sum_ + self.tree[k] < x:
				sum_ += self.tree[k]
				pos += 1 << i
		return pos + 1
q = sorted(enumerate(ppp, 1), key=itemgetter(1), reverse=True)
bit = Bit(n + 4)
bit.add(1, 1)
bit.add(2, 1)
bit.add(n + 3, 1)
bit.add(n + 4, 1)
ans = 0
for (i, p) in q:
	f = bit.sum(i + 2)
	LL = max(2, bit.lower_bound(f - 1))
	LR = bit.lower_bound(f)
	RL = bit.lower_bound(f + 1)
	RR = min(n + 3, bit.lower_bound(f + 2))
	ans += p * ((i + 2 - LR) * (RR - RL) + (LR - LL) * (RL - i - 2))
	bit.add(i + 2, 1)
print(ans)


N = int(input())
P = [int(i) for i in input().split()]
ind = [0] * (N + 1)
for i in range(N):
	ind[P[i]] = i + 1
ans = 0
l = [0] + [f for f in range(N + 1)]
r = [f + 1 for f in range(N + 1)] + [N + 1]
for j in range(1, N + 1):
	f = ind[j]
	l1 = l[f]
	l2 = l[l1]
	r1 = r[f]
	r2 = r[r1]
	ans += ((l1 - l2) * (r1 - f) + (f - l1) * (r2 - r1)) * j
	l[r1] = l1
	r[l1] = r1
print(ans)


import sys

def solve(N: int, P: 'List[int]'):
	pos = {n: i + 1 for (i, n) in enumerate(P)}
	L1 = list(range(-1, N + 1))
	L1[0] = 0
	L2 = list(range(-2, N))
	L2[0] = 0
	L2[1] = 0
	R1 = list(range(1, N + 3))
	R1[-1] = N + 1
	R2 = list(range(2, N + 4))
	R2[-1] = N + 1
	R2[-2] = N + 1
	res = 0
	for i in range(1, N + 1):
		s = pos[i]
		num = 0
		num += (R2[s] - R1[s]) * (s - L1[s])
		num += (L1[s] - L2[s]) * (R1[s] - s)
		res += i * num
		L1[R1[s]] = L1[s]
		L2[R1[s]] = L2[s]
		L2[R2[s]] = L1[s]
		R1[L1[s]] = R1[s]
		R2[L1[s]] = R2[s]
		R2[L2[s]] = R1[s]
	print(res)
	return

def main():

	def iterate_tokens():
		for line in sys.stdin:
			for word in line.split():
				yield word
	tokens = iterate_tokens()
	N = int(next(tokens))
	P = [int(next(tokens)) for _ in range(N)]
	solve(N, P)
main()


import bisect
N = int(input())
P = sorted(enumerate(map(int, input().split())), key=lambda x: x[1])[::-1]
used = [-1, P[0][0], N]
ans = 0
for (i, p) in P[1:]:
	idx = bisect.bisect_left(used, i)
	d = 0
	if idx != 1:
		d += (used[idx] - i) * (used[idx - 1] - used[idx - 2])
	if idx != len(used) - 1:
		d += (i - used[idx - 1]) * (used[idx + 1] - used[idx])
	ans += p * d
	used.insert(idx, i)
print(ans)


class BIT:

	def __init__(self, n):
		self.n = n
		self.bit = [0] * (n + 10)

	def add(self, x, w):
		while x <= self.n:
			self.bit[x] += w
			x += x & -x

	def sum(self, x):
		cnt = 0
		while x > 0:
			cnt += self.bit[x]
			x -= x & -x
		return cnt

	def psum(self, a, b):
		return self.sum(b - 1) - self.sum(a - 1)

	def bisect(self, w):
		x = 0
		k = 1
		while k < self.n:
			k *= 2
		while k > 0:
			if x + k <= self.n and self.bit[x + k] < w:
				w -= self.bit[x + k]
				x += k
			k //= 2
		return x + 1
n = int(input())
ps = list(map(int, input().split()))
inds = [0] * (n + 1)
for (i, p) in enumerate(ps):
	inds[p] = i + 1
bit = BIT(n)
cnt = 0
for p in range(n, 0, -1):
	ind = inds[p]
	nl = bit.sum(ind)
	nr = n - p - nl
	bit.add(ind, 1)
	ixl2 = bit.bisect(nl - 1) if nl >= 2 else 0
	ixl1 = bit.bisect(nl) if nl >= 1 else 0
	ixr1 = bit.bisect(nl + 2) if nr >= 1 else n + 1
	ixr2 = bit.bisect(nl + 3) if nr >= 2 else n + 1
	tmp = 0
	tmp += (ixl1 - ixl2) * (ixr1 - ind)
	tmp += (ixr2 - ixr1) * (ind - ixl1)
	cnt += p * tmp
print(cnt)


class BIT:

	def __init__(self, n):
		self.N = n
		self.tree = [0] * (n + 1)

	def BIT_add(self, i):
		while i <= self.N:
			self.tree[i] += 1
			i += i & -i

	def BIT_sum(self, i):
		s = 0
		while i:
			s += self.tree[i]
			i -= i & -i
		return s

	def BIT_search(self, x):
		i = 0
		s = 0
		step = 1 << self.N.bit_length() - 1
		while step:
			if i + step <= self.N and s + self.tree[i + step] < x:
				i += step
				s += self.tree[i]
			step >>= 1
		return i + 1
N = int(input())
bit = BIT(N)
p = [None] + [int(c) for c in input().split()]
p_to_i = [None] * (N + 1)
for (i, x) in enumerate(p[1:], 1):
	p_to_i[x] = i
ans = 0
for x in range(N, 0, -1):
	c = p_to_i[x]
	L = bit.BIT_sum(c)
	bit.BIT_add(c)
	R = N - x - L
	a = bit.BIT_search(L - 1) if L >= 2 else 0
	b = bit.BIT_search(L) if L >= 1 else 0
	d = bit.BIT_search(L + 2) if R >= 1 else N + 1
	e = bit.BIT_search(L + 3) if R >= 1 else N + 1
	coef = 0
	if b != 0:
		coef += (b - a) * (d - c)
	if d != 0:
		coef += (e - d) * (c - b)
	ans += x * coef
print(ans)


class BIT:

	def __init__(self, N):
		self.N = N
		self.bit = [0] * (N + 1)
		self.b = 1 << N.bit_length() - 1

	def add(self, a, w):
		x = a
		while x <= self.N:
			self.bit[x] += w
			x += x & -x

	def get(self, a):
		(ret, x) = (0, a - 1)
		while x > 0:
			ret += self.bit[x]
			x -= x & -x
		return ret

	def cum(self, l, r):
		return self.get(r) - self.get(l)

	def lowerbound(self, w):
		if w <= 0:
			return 0
		x = 0
		k = self.b
		while k > 0:
			if x + k <= self.N and self.bit[x + k] < w:
				w -= self.bit[x + k]
				x += k
			k //= 2
		return x + 1
N = int(input())
P = list(map(int, input().split()))
dic = {}
bit = BIT(N)
for i in range(N):
	dic[P[i]] = i + 1
dic[0] = 0
dic[N + 1] = N + 1
ans = 0
ng = [0, N + 1]
for i in reversed(range(1, N + 1)):
	bit.add(dic[i], 1)
	c = bit.get(dic[i] + 1)
	(l1, l2) = (bit.lowerbound(c - 1), bit.lowerbound(c - 2))
	(r1, r2) = (bit.lowerbound(c + 1), bit.lowerbound(c + 2))
	S = (l1 - l2) * (r1 - dic[i]) + (r2 - r1) * (dic[i] - l1)
	ans += S * i
print(ans)


class BIT:

	def __init__(self, n):
		self.n = n
		self.data = [0] * (n + 1)

	def ope(self, x, y):
		return x + y

	def update(self, i, v):
		while i <= self.n:
			self.data[i] = self.ope(self.data[i], v)
			i += i & -i

	def query(self, i):
		ret = 0
		while 0 < i:
			ret = self.ope(self.data[i], ret)
			i &= i - 1
		return ret

	def lowerBound(self, w):
		if w <= 0:
			return 0
		(x, k) = (0, 2 ** self.n.bit_length())
		while k:
			if x + k <= self.n and self.data[x + k] < w:
				w -= self.data[x + k]
				x += k
			k >>= 1
		return x + 1
n = int(input())
p = list(map(int, input().split()))
pos = [0] * n
for (i, pi) in enumerate(p):
	pos[pi - 1] = i
bit1 = BIT(n)
bit2 = BIT(n)
ans = 0
for pi in range(n, 0, -1):
	i = pos[pi - 1]
	cur = bit1.query(i + 1)
	if cur == 0:
		left_0 = i + 1
		left_1 = 0
	else:
		tmp = bit1.lowerBound(cur)
		tmp2 = bit1.lowerBound(cur - 1)
		left_0 = i + 1 - tmp
		left_1 = tmp - tmp2
	bit1.update(i + 1, 1)
	j = n - i - 1
	cur = bit2.query(j + 1)
	if cur == 0:
		right_0 = j + 1
		right_1 = 0
	else:
		tmp = bit2.lowerBound(cur)
		tmp2 = bit2.lowerBound(cur - 1)
		right_0 = j + 1 - tmp
		right_1 = tmp - tmp2
	bit2.update(j + 1, 1)
	ans += pi * (left_0 * right_1 + left_1 * right_0)
print(ans)


from heapq import heappush, heappop
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations
import sys
import bisect
import string
import math
import time
import random

def I():
	return int(input())

def MI():
	return map(int, input().split())

def LI():
	return [int(i) for i in input().split()]

def LI_():
	return [int(i) - 1 for i in input().split()]

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
YN = ['Yes', 'No']
mo = 10 ** 9 + 7
ts = time.time()
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
show_flg = False

class Bit:

	def __init__(self, n):
		self.size = n
		self.m = len(bin(self.size)) - 2
		self.arr = [0] * (2 ** self.m + 1)

	def __str__(self):
		return str(self.arr)

	def add(self, i, x):
		k = 0
		while i <= self.size:
			k += 1
			self.arr[i] += x
			i += i & -i
		return

	def sum(self, i):
		rt = 0
		while i > 0:
			rt += self.arr[i]
			i -= i & -i
		return rt

	def l_bound(self, w):
		if w <= 0:
			return 0
		x = 0
		k = 2 ** self.m
		while k > 0:
			if x + k < self.size and self.arr[x + k] < w:
				w -= self.arr[x + k]
				x += k
			k //= 2
		return x + 1

class Bit0(Bit):

	def add(self, j, x):
		super().add(j + 1, x)

	def l_bound(self, w):
		return max(super().l_bound(w) - 1, 0)
n = I()
a = LI()
p = [i + 1 for (i, j) in sorted(enumerate(a), key=lambda x: x[1])]
bt = Bit0(n + 2)
bt.add(0, 1)
bt.add(n + 1, 1)
ans = 0
for i in range(n - 1, -1, -1):
	c = bt.sum(p[i])
	(w, x, y, z) = [bt.l_bound(c - 1 + i) for i in range(4)]
	c = p[i]
	bt.add(p[i], 1)
	d = (i + 1) * ((x - w) * (y - c) + (c - x) * (z - y))
	ans += d
print(ans)


ans = 0
n = int(input())
p = list(map(int, input().split()))
b = [0] * (n + 1)
for i in range(n):
	b[p[i]] = i + 1
LL = [0] + [i for i in range(n + 1)]
RR = [i for i in range(1, n + 2)] + [n + 1]
for i in range(1, n + 1):
	l1 = LL[b[i]]
	l0 = LL[l1]
	r0 = RR[b[i]]
	r1 = RR[r0]
	ans += ((l1 - l0) * (r0 - b[i]) + (r1 - r0) * (b[i] - l1)) * i
	LL[r0] = l1
	RR[l1] = r0
print(ans)


class BinaryIndexTree:

	def __init__(self, N):
		if isinstance(N, int):
			self.N = N
			self.depth = N.bit_length()
			self.tree = [0] * (N + 1)
			self.elem = [0] * (N + 1)
		elif isinstance(N, list):
			self.N = len(N)
			self.depth = self.N.bit_length()
			self.tree = [0] + N
			self.elem = [0] + N
			self._init()
		else:
			raise 'INVALID INPUT: input must be int or list'

	def _init(self):
		size = self.N + 1
		for i in range(1, self.N):
			if i + (i & -i) > size:
				continue
			self.tree[i + (i & -i)] += self.tree[i]

	def add(self, i, x):
		self.elem[i] += x
		while i <= self.N:
			self.tree[i] += x
			i += i & -i

	def sum(self, i):
		res = 0
		while i > 0:
			res += self.tree[i]
			i -= i & -i
		return res

	def lower_bound(self, val):
		if val <= 0:
			return 0
		i = 0
		k = 1 << self.depth
		while k:
			if i + k <= self.N and self.tree[i + k] < val:
				val -= self.tree[i + k]
				i += k
			k >>= 1
		return i + 1
N = int(input())
P = list(map(int, input().split()))
p_to_i = {p: i for (i, p) in enumerate(P, start=1)}
bit = BinaryIndexTree(N)
bit.add(p_to_i[N], 1)
ans = 0
for p in range(N - 1, 0, -1):
	cnt = N - p + 1
	i = p_to_i[p]
	bit.add(i, 1)
	Bsum = bit.sum(i)
	l2 = max(0, bit.lower_bound(Bsum - 2))
	l1 = bit.lower_bound(Bsum - 1)
	r1 = bit.lower_bound(Bsum + 1)
	r2 = min(N + 1, bit.lower_bound(Bsum + 2))
	CL = (l1 - l2) * (r1 - i)
	CR = (r2 - r1) * (i - l1)
	C = CL + CR
	ans += p * C
print(ans)


N = int(input())
P = [0] + list(map(int, input().split())) + [N + 1]
ans = 0
b = [0] * (N + 2)
for i in range(N + 2):
	b[P[i]] = i
l1 = [max(0, i - 1) for i in range(N + 2)]
l2 = [max(0, i - 2) for i in range(N + 2)]
r1 = [min(N + 1, i + 1) for i in range(N + 2)]
r2 = [min(N + 1, i + 2) for i in range(N + 2)]
for i in range(N + 1):
	m = b[i]
	(x2, x1, y1, y2) = (l2[m], l1[m], r1[m], r2[m])
	hoge = i * (abs((m - x1) * (y2 - y1)) + abs((y1 - m) * (x1 - x2)))
	ans += hoge
	r1[x1] = y1
	r2[x1] = y2
	l1[y1] = x1
	l2[y1] = x2
	r1[x2] = x1
	r2[x2] = y1
	l1[y2] = y1
	l2[y2] = x1
print(ans)


import sys
input = sys.stdin.readline

def main():
	n = int(input()[:-1])
	aa = list(map(int, input().split()))
	ans = 0
	pos = [0] * (n + 1)
	for (i, a) in enumerate(aa):
		pos[a] = i + 2
	Lnext = [1, 1] + list(range(1, n + 1)) + [n, n]
	Rnext = [3, 3] + list(range(3, n + 3)) + [n + 2, n + 2]
	for a in range(1, n + 1):
		i = pos[a]
		l0 = Lnext[i]
		l1 = Lnext[l0]
		r0 = Rnext[i]
		r1 = Rnext[r0]
		ans += a * ((l0 - l1) * (r0 - i) + (i - l0) * (r1 - r0))
		Lnext[r0] = l0
		Rnext[l0] = r0
	print(ans)
main()


class BIT:

	def __init__(self, N):
		self.n = N
		self.tree = [0] * (self.n + 1)

	def bsum(self, i):
		s = 0
		while i:
			s += self.tree[i]
			i -= i & -i
		return s

	def badd(self, i, x):
		while i <= self.n:
			self.tree[i] += x
			i += i & -i

	def bsearch(self, x):
		i = 0
		s = 0
		step = 1 << self.n.bit_length() - 1
		while step:
			if i + step <= self.n and s + self.tree[i + step] < x:
				i += step
				s += self.tree[i]
			step >>= 1
		return i + 1
N = int(input())
P = [0] + [int(c) for c in input().split()]
ntoi = [0] * (N + 1)
for i in range(N + 1):
	ntoi[P[i]] = i
bit = BIT(N)
ans = 0
for m in range(N, 0, -1):
	I = ntoi[m]
	L = bit.bsum(I)
	bit.badd(I, 1)
	R = N - L - m
	a = bit.bsearch(L - 1) if L > 1 else 0
	b = bit.bsearch(L) if L > 0 else 0
	c = bit.bsearch(L + 2) if R > 0 else N + 1
	d = bit.bsearch(L + 3) if R > 1 else N + 1
	coef = 0
	if b != 0:
		coef += (b - a) * (c - I)
	if c != 0:
		coef += (I - b) * (d - c)
	ans += m * coef
print(ans)


(N, *P) = map(int, open(0).read().split())
idx_dict = [0] * (N + 1)
for i in range(N):
	idx_dict[P[i]] = i + 1
cnt = 0
l = [0] + [i for i in range(N + 1)]
r = [i + 1 for i in range(N + 1)] + [N + 1]
for v in range(1, N + 1):
	i = idx_dict[v]
	l1 = l[i]
	l2 = l[l1]
	r1 = r[i]
	r2 = r[r1]
	cnt += ((l1 - l2) * (r1 - i) + (i - l1) * (r2 - r1)) * v
	l[r1] = l1
	r[l1] = r1
print(cnt)