Problem:
 Score: 500 points    Problem Statement  Given is a permutation P of \{1, 2, \ldots, N\} .  For a pair (L, R) (1 \le L \lt R \le N) , let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R .  Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R} .      Constraints   2 \le N \le 10^5  1 \le P_i \le N  P_i \neq P_j  (i \neq j)  All values in input are integers.         Input  Input is given from Standard Input in the following format:  N  P_1  P_2  \ldots  P_N       Output  Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R} .        Sample Input 1 3
2 3 1      Sample Output 1 5  X_{1, 2} = 2, X_{1, 3} = 2 , and X_{2, 3} = 1 , so the sum is 2 + 2 + 1 = 5 .       Sample Input 2 5
1 2 3 4 5      Sample Output 2 30       Sample Input 3 8
8 2 7 3 4 5 6 1      Sample Output 3 136

Solution (Python):
import subprocess
import gzip, base64, os
import stat

gz = b'H4sIAIVrdF0C/+19fXxT1f3/TdKW8NQELazyIEGqFJHSQoHWxxQauIEUkAKyKYY0SWk1TbrmBouiVts6Y6iiP+f8urmxzW1uc9Pt6xT9OiiCFBUUH3hQfEAHckNB0ClWHeT3+Zxzbnruzb0VnL/vH7/XovTk8z6f8/D5nM/5nId7c86tLs8ss8kkKB+zcLmA1A9HOAntZHiLP80CWJnQH/6OFkYKOUBnc3xOwakKe1jWSmhlfBb4lwX/ysyULjM7VeFIxqeEJi7MFviPUxX+6ypBFQqCI50O67p3GUX3LluuCq1ZFLf3U6czs3Q9LF0P41dCwSyoQkW+LPZvEcMXMbmUsJLxVXL8+FlwUArgd3EhpcWFTlW4mvGt1qS7EtLlCKf/sbNwISvPSC+FrP5KqLTDpFB9zbTSSaHAxFB9ONY8sbls2sRppUXRSNFkUic74509b7FKj/msznnMBjC+8JrOlpOPTH/4pq8OXh74sPjx43WzVmJcGUuHTdIettdljelvNgmlQgtkjXGXsFb/6ztTdg24ba33Yf/fX7i7IbXtznb/sDer17Wu+b7zk4mf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1Hlningc1cF09696XTytxj2fVephpfereiPxojkQrqEM7y2U1sD3RttM6qpe+euiquo/LRuDyY3VGZmz92DqaOiPq71VdehpERg2tG/S1OdN721kmHsMkpyFaYayrjVUhPd5+WlWmkyrgHVtnLvVZuZxRhcuZvZpIbX42aUhq9fQJuHQt70ZcLf7vJgdc7k/lAdATIvF9bUqM/bped7ye+mvLFoMJB5qbCmBk3BYEYF+rr6V52cXn2qyaCP6621nd7wBms9886421XXTehdUK3Tk3Sun9Vy6dxorDUMEE/xiBn3OWfaG7kGOBPmLqjW5h+IRrx1MNKC8ui9s7p9Dr0dm0J9hxdpZ/gtzZ3PWkEyb0vWSlMTjXKNn74wPEPvp3WLsNPJ3YibefexrsPIuAg5MxP1ZdF6uahvYlfnoHt/u8G15xovSy4M1vEF3+76b00vD0ZqtZaTviRdLQEZtr/dFdyaMskvJ7UCnf4N2DojsM619EY92+B2cb325K4n16iCvBqmd694ptl8B/dn64yBOtKlL6/XxKkurYY4dpm09k76TK0q14vrTGboBeE6ldDenp5pyo2relu+pDTzEm7tFKM+LFAX9n8BK6yodPyKAAA='
bin = gzip.decompress(base64.b64decode(gz))
p = os.path.dirname(__file__)
pymain = os.path.join(p, "a.out")
with open(pymain, "wb") as f:
    f.write(bin)
os.chmod(pymain, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
if p == "":
    pymain = "./" + pymain
subprocess.call(pymain)



'''

import numpy as np

def solve(P):
    N = P.shape[0]
    top = np.empty(N, dtype=np.int64)
    second = np.empty(N, dtype=np.int64)
    count = np.empty(N, dtype=np.int64)
    sum = np.empty(N + 1, dtype=np.int64)

    sum[N] = 0
    p = N - 1
    top[p] = P[N - 1]
    second[p] = 0
    count[p] = 1
    sum[p] = 0
    ans = 0
    for j in range(N - 2, -1, -1):
        x = P[j]
        pt = N 
        for i in range(p, N):
            if x < top[i]:
                pt = i
                break
        ps = N
        for i in range(pt, N):
            if x < second[i]:
                ps = i
                break
        asum = sum[ps]
        ccount = 0
        psum = ps - 1
        for i in range(ps - 1, pt, -1):
            ccount += count[i]
            if top[i - 1] != top[i]:
                second[psum] = x
                asum += x * ccount
                sum[psum] = asum
                count[psum] = ccount
                ccount = 0
                psum -= 1
        if pt < ps:
            ccount += count[pt]
            second[psum] = x
            asum += x * ccount
            sum[psum] = asum
            count[psum] = ccount
            ccount = 0
            psum -= 1
        for i in range(pt - 1, p, -1):
            ccount += count[i]
            if top[i - 1] != top[i]:
                asum += top[i] * ccount
                sum[psum] = asum
                second[psum] = top[i]
                top[psum] = x
                count[psum] = ccount
                ccount = 0
                psum -= 1
        if p < pt:
            ccount += count[p]
            asum += top[p] * ccount
            sum[psum] = asum
            second[psum] = top[p]
            top[psum] = x
            count[psum] = ccount
            psum -= 1

        top[psum] = x
        second[psum] = 0
        sum[psum] = asum
        count[psum] = 1
        ans += asum
        p = psum
    return ans


def main2():
    stdin = open('/dev/stdin')
    N = int(stdin.readline())
    P = np.empty(N, dtype=np.int64)
    i = 0
    for s in stdin.readline().split():
        P[i] = int(s)
        i += 1
    ans = solve(P)
    print(ans)
'''

Solution (Python):
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):
        s = 0
        while index:
            s += self.tree[index]
            index -= index & (-index)
        return s

    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.tree[i + step] < val:
                i += step
                s += self.tree[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()

Solution (Python):
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)

Solution (Python):
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()

Solution (Python):
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)

Solution (Python):
import sys

stdin = sys.stdin

ni = lambda: int(ns())
nl = lambda: list(map(int, stdin.readline().split()))
nm = lambda: 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)

Solution (Python):
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))

Solution (Python):
class SegmentTree:
    def __init__(self, n, init_value):
        self.n = n
        n2 = 1  
        while n2 < n:
            n2 <<= 1
        self.n2 = n2
        self.tree = [[init_value, init_value] for _ in range(n2 << 1)]
        self.ini = init_value

    def update(self, i, x):
        
        i += self.n2
        self.tree[i][0] = x
        while i > 1:
            i >>= 1
            sti = self.tree[i]
            if sti[0] > x:
                sti[1] = sti[0]
                sti[0] = x
            elif sti[1] > x:
                sti[1] = x

    def get(self, a, b):
        result = [self.ini, self.ini]
        q = [(1, 0, self.n2)]

        while q:
            k, l, r = q.pop()

            if a <= l and r <= b:
                stk = self.tree[k]
                if result[0] > stk[0]:
                    result[1] = min(result[0], stk[1])
                    result[0] = stk[0]
                elif result[1] > stk[0]:
                    result[1] = stk[0]
                continue

            m = (l + r) // 2
            k <<= 1
            if a < m and l < b:
                q.append((k, l, m))
            if a < r and l < m:
                q.append((k + 1, m, r))

        return result


def solve(n, ppp):
    str = SegmentTree(n, n)
    right = []
    for i in range(n - 1, -1, -1):
        p = ppp[i]
        right.append(str.get(p, n))
        str.update(p - 1, i)
    right.reverse()

    ans = 0
    stl = SegmentTree(n, 1)
    for i in range(n):
        p = ppp[i]
        l1, l2 = stl.get(p, n)
        l1, l2 = -l1, -l2
        r1, r2 = right[i]
        ans += p * ((l1 - l2) * (r1 - i) + (r2 - r1) * (i - l1))
        stl.update(p - 1, -i)

    return ans


n = int(input())
ppp = list(map(int, input().split()))
print(solve(n, ppp))

Solution (Python):
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)