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



Sample input:
3
2 3 1


Sample output:
5

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
from bisect import bisect_left, bisect_right
from operator import itemgetter
from fractions import gcd
from math import ceil, floor, sqrt
from copy import deepcopy
from collections import Counter, deque
import heapq
from functools import reduce
sys.setrecursionlimit(200000)
# local only
# if not __debug__:
#     fin = open('in_1.txt', 'r')
#     sys.stdin = fin
# local only
input = sys.stdin.readline
def ii(): return int(input())
def mi(): return map(int, input().rstrip().split())
def lmi(): return list(map(int, input().rstrip().split()))
def li(): return list(input().rstrip())
def debug(*args, sep=" ", end="\n"): print("debug:", *args, file=sys.stderr, sep=sep, end=end) if not __debug__ else None
def exit(*arg): print(*arg); sys.exit()
# template

class Avltree:
    """
    AVL木

    Methods
    -------
        search(x: int) -> Union(int)
            ◯.data == x のものが存在するある場合それを出力、ない場合 None を返す
        insert(x: int) -> None
            ◯.data == x がない場合 ◯.data == x なる頂点を作る。ある場合はなにもしない（上書きしない）
        y.to_s() -> int
            頂点yのdataを返す
        y.left_s() -> Union(int, key=None)
            頂点yのleftを返す(ない場合は key)
        search_lower(x: int, key_lower) -> int
            ○.data が x より小さいものの中で最も大きいものを出力、ない場合 key_lower を返す
        search_higher(x:int , key_higher) -> int
            ○.data が x より大きいものの中で最も小さいものを出力、ない場合 key_higher を返す
    """

    def __init__(self, key=None):
        self.key = key
        self.left = None
        self.right = None
        self.balance = "Even"
    def search(self, key):
        if self.key is None:
            return None
        if self.key > key:
            if self.left is None:
                return None
            else:
                return self.left.search(key)
        if self.key < key:
            if self.right is None:
                return None
            else:
                return self.right.search(key)
        return self  # self.key == keyの場合

    def search_lower(self, key, key_lower):
        if self.key is None:
            return key_lower
        if self.key > key:
            if self.left is None:
                return key_lower
            else:
                return self.left.search_lower(key, key_lower)
        if self.key < key:
            key_lower = self.key
            if self.right is None:
                return key_lower
            else:
                return self.right.search_lower(key, key_lower)
        # self.key == keyの場合
        if self.left is None:
            return key_lower
        else:
            if key_lower is None:
                return self.left.end_higher(self.left.key)
            else:
                return max(key_lower, self.left.end_higher(self.left.key))

    def search_higher(self, key, key_higher):
        if self.key is None:
            return key_higher
        if self.key > key:
            key_higher = self.key
            if self.left is None:
                return key_higher
            else:
                return self.left.search_higher(key, key_higher)
        if self.key < key:
            if self.right is None:
                return key_higher
            else:
                return self.right.search_higher(key, key_higher)
        # self.key == keyの場合
        if self.right is None:
            return key_higher
        else:
            if key_higher is None:
                return self.right.end_lower(self.right.key)
            else:
                return min(key_higher, self.right.end_lower(self.right.key))


    def end_lower(self, end_lower_key):
        if self.left is None:
            return end_lower_key
        else:
            end_lower_key = self.left.key
            return self.left.end_lower(end_lower_key)
    def end_higher(self, end_higher_key):
        if self.right is None:
            return end_higher_key
        else:
            end_higher_key = self.right.key
            return self.right.end_higher(end_higher_key)


    def DoubleRightRotation(self):
        tl = self.left
        self.left = tl.right.right
        tl.right.right = self  # selfはそのノード
        tlr = tl.right
        tl.right = tlr.left
        tlr.left = tl
        if tlr.balance == "Left":
            tlr.right.balance = "Right"
            tlr.left.balance = "Even"
        elif tlr.balance == "Right":
            tlr.right.balance = "Even"
            tlr.left.balance = "Left"
        elif tlr.balance == "Even":
            tlr.right.balance = "Even"
            tlr.left.balance = "Even"
        tlr.balance = "Even"
        return tlr
    def DoubleLeftRotation(self):
        tr = self.right
        self.right = tr.left.left
        tr.left.left = self
        trl = tr.left
        tr.left = trl.right
        trl.right = tr
        if trl.balance == "Right":
            trl.left.balance = "Left"
            trl.right.balance = "Even"
        elif trl.balance == "Left":
            trl.left.balance = "Even"
            trl.right.balance = "Right"
        elif trl.balance == "Even":
            trl.left.balance = "Even"
            trl.right.balance = "Even"
        trl.balance = "Even"
        return trl
    def SingleLeftRotation(self):
        tr = self.right
        tr.balance = "Even"
        self.balance = "Even"
        self.right = tr.left
        tr.left = self
        return tr
    def SingleRightRotation(self):
        tl = self.left
        tl.balance = "Even"
        self.balance = "Even"
        self.left = tl.right
        tl.right = self
        return tl
    def replace(self, p, v):  # 親ノードpの下にある自分(self)をvに置き換える。
        if p.left == self:
            p.left = v
        else:
            p.right = v
    def insert(self, key):  # rootでのみ呼ばれる挿入
        if self.key is None:  # rootを含むrotationはしないことにする。
            self.key = key
            return self
        if key < self.key:
            if self.left is None:
                self.left = Avltree(key)
            else:
                self.left.insertx(self, key)
        elif key > self.key:
            if self.right is None:
                self.right = Avltree(key)
            else:
                self.right.insertx(self, key)
        else:  # key == self.key:
            pass  # do not overwrite
    def insertx(self, p, key):  # replaceを呼ぶために一つ上の親を持っているinsert
        if self.key > key:
            if self.left is None:
                self.left = Avltree(key)
            else:
                if not self.left.insertx(self, key):  # 左の木が生長しなければ、
                    return False  # 成長しない
            if self.balance == "Right":
                self.balance = "Even"
                return False
            elif self.balance == "Even":
                self.balance = "Left"
                return True  # 成長した
            elif self.balance == "Left":
                if self.left.balance == "Right":
                    self.replace(p, self.DoubleRightRotation())
                elif self.left.balance == "Left":
                    self.replace(p, self.SingleRightRotation())
                return False  # rotationを行うと成長しない
        if self.key < key:
            if self.right is None:
                self.right = Avltree(key)
            else:
                if not self.right.insertx(self, key):
                    return False
            if self.balance == "Left":
                self.balance = "Even"
                return False
            elif self.balance == "Even":
                self.balance = "Right"
                return True
            elif self.balance == "Right":
                if self.right.balance == "Left":
                    self.replace(p, self.DoubleLeftRotation())
                elif self.right.balance == "Right":
                    self.replace(p, self.SingleLeftRotation())
                return False
        return False  # self.key == key の時は何もしないので成長もしない

    def to_s(self):
        return self.key
    def left_s(self):
        if self.left is None:
            return None
        return (self.left).key
    def right_s(self):
        if self.right is None:
            return None
        return (self.right).key

def main():
    N = ii()
    P = lmi()
    L = []
    for i in range(N):
        L.append((P[i], i))
    L.sort(key=itemgetter(0), reverse=True)
    # print(L)
    ans = 0
    rb = Avltree()
    for x, i in L:
        rb.insert(i)
        l1 = rb.search_lower(i, -1)
        l2 = rb.search_lower(l1, -1)
        r1 = rb.search_higher(i, N)
        r2 = rb.search_higher(r1, N)
        # print(l2, l1, r1, r2)
        ans += (abs(i - l1) * abs(r2 - r1) + abs(l1 - l2) * abs(r1 - i)) * x
    print(ans)
    return



if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import heapq

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

dic = [0] * n
for i in range(n):
    dic[p[i]-1] = i+1

ans = 0
big = {0,n+1}
big.add(dic[n-1])
for i in range(n-1,0,-1):
    i_no = dic[i-1]
    bigger = big & set(range(i_no+1,n+2,1))
    smaller = big & set(range(i_no-1,-1,-1))

    if len(bigger)==1:
        r1 = n+1
        r2 = n+1
    else:
        r1, r2 = heapq.nsmallest(2, bigger)
        # r1 = min(bigger)
        # bigger.discard(r1)
        # r2 = min(bigger)

    if len(smaller)==1:
        l1 = 0
        l2 = 0
    else:
        l1, l2 = heapq.nlargest(2, smaller)
        # l1 = max(smaller)
        # smaller.discard(l1)
        # l2 = max(smaller)

    ans += i*((r2-r1)*(i_no-l1)+(r1-i_no)*(l1-l2))

    big.add(i_no)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
from bisect import bisect_left, bisect_right
from operator import itemgetter
from fractions import gcd
from math import ceil, floor, sqrt
from copy import deepcopy
from collections import Counter, deque
import heapq
from functools import reduce
sys.setrecursionlimit(200000)
# local only
# if not __debug__:
#     fin = open('in_1.txt', 'r')
#     sys.stdin = fin
# local only
input = sys.stdin.readline
def ii(): return int(input())
def mi(): return map(int, input().rstrip().split())
def lmi(): return list(map(int, input().rstrip().split()))
def li(): return list(input().rstrip())
def debug(*args, sep=" ", end="\n"): print("debug:", *args, file=sys.stderr, sep=sep, end=end) if not __debug__ else None
def exit(*arg): print(*arg); sys.exit()
# template

class Avltree:
    """
    AVL木

    Methods
    -------
        search(x: int) -> Union(int)
            ◯.data == x のものが存在するある場合それを出力、ない場合 None を返す
        insert(x: int) -> None
            ◯.data == x がない場合 ◯.data == x なる頂点を作る。ある場合はなにもしない（上書きしない）
        y.to_s() -> int
            頂点yのdataを返す
        y.left_s() -> Union(int, key=None)
            頂点yのleftを返す(ない場合は key)
        search_lower(x: int, key_lower) -> int
            ○.data が x より小さいものの中で最も大きいものを出力、ない場合 key_lower を返す
        search_higher(x:int , key_higher) -> int
            ○.data が x より大きいものの中で最も小さいものを出力、ない場合 key_higher を返す
    """

    def __init__(self, key=None):
        self.key = key
        self.left = None
        self.right = None
        self.balance = "Even"
    def search(self, key):
        if self.key is None:
            return None
        if self.key > key:
            if self.left is None:
                return None
            else:
                return self.left.search(key)
        if self.key < key:
            if self.right is None:
                return None
            else:
                return self.right.search(key)
        return self  # self.key == keyの場合

    def search_lower(self, key, key_lower):
        if self.key is None:
            return key_lower
        if self.key > key:
            if self.left is None:
                return key_lower
            else:
                return self.left.search_lower(key, key_lower)
        if self.key < key:
            key_lower = self.key
            if self.right is None:
                return key_lower
            else:
                return self.right.search_lower(key, key_lower)
        # self.key == keyの場合
        if self.left is None:
            return key_lower
        else:
            if key_lower is None:
                return self.left.end_higher(self.left.key)
            else:
                return max(key_lower, self.left.end_higher(self.left.key))

    def search_higher(self, key, key_higher):
        if self.key is None:
            return key_higher
        if self.key > key:
            key_higher = self.key
            if self.left is None:
                return key_higher
            else:
                return self.left.search_higher(key, key_higher)
        if self.key < key:
            if self.right is None:
                return key_higher
            else:
                return self.right.search_higher(key, key_higher)
        # self.key == keyの場合
        if self.right is None:
            return key_higher
        else:
            if key_higher is None:
                return self.right.end_lower(self.right.key)
            else:
                return min(key_higher, self.right.end_lower(self.right.key))


    def end_lower(self, end_lower_key):
        if self.left is None:
            return end_lower_key
        else:
            end_lower_key = self.left.key
            return self.left.end_lower(end_lower_key)
    def end_higher(self, end_higher_key):
        if self.right is None:
            return end_higher_key
        else:
            end_higher_key = self.right.key
            return self.right.end_higher(end_higher_key)


    def DoubleRightRotation(self):
        tl = self.left
        self.left = tl.right.right
        tl.right.right = self  # selfはそのノード
        tlr = tl.right
        tl.right = tlr.left
        tlr.left = tl
        if tlr.balance == "Left":
            tlr.right.balance = "Right"
            tlr.left.balance = "Even"
        elif tlr.balance == "Right":
            tlr.right.balance = "Even"
            tlr.left.balance = "Left"
        elif tlr.balance == "Even":
            tlr.right.balance = "Even"
            tlr.left.balance = "Even"
        tlr.balance = "Even"
        return tlr
    def DoubleLeftRotation(self):
        tr = self.right
        self.right = tr.left.left
        tr.left.left = self
        trl = tr.left
        tr.left = trl.right
        trl.right = tr
        if trl.balance == "Right":
            trl.left.balance = "Left"
            trl.right.balance = "Even"
        elif trl.balance == "Left":
            trl.left.balance = "Even"
            trl.right.balance = "Right"
        elif trl.balance == "Even":
            trl.left.balance = "Even"
            trl.right.balance = "Even"
        trl.balance = "Even"
        return trl
    def SingleLeftRotation(self):
        tr = self.right
        tr.balance = "Even"
        self.balance = "Even"
        self.right = tr.left
        tr.left = self
        return tr
    def SingleRightRotation(self):
        tl = self.left
        tl.balance = "Even"
        self.balance = "Even"
        self.left = tl.right
        tl.right = self
        return tl
    def replace(self, p, v):  # 親ノードpの下にある自分(self)をvに置き換える。
        if p.left == self:
            p.left = v
        else:
            p.right = v
    def insert(self, key):  # rootでのみ呼ばれる挿入
        if self.key is None:  # rootを含むrotationはしないことにする。
            self.key = key
            return self
        if key < self.key:
            if self.left is None:
                self.left = Avltree(key)
            else:
                self.left.insertx(self, key)
        elif key > self.key:
            if self.right is None:
                self.right = Avltree(key)
            else:
                self.right.insertx(self, key)
        else:  # key == self.key:
            pass  # do not overwrite
    def insertx(self, p, key):  # replaceを呼ぶために一つ上の親を持っているinsert
        if self.key > key:
            if self.left is None:
                self.left = Avltree(key)
            else:
                if not self.left.insertx(self, key):  # 左の木が生長しなければ、
                    return False  # 成長しない
            if self.balance == "Right":
                self.balance = "Even"
                return False
            elif self.balance == "Even":
                self.balance = "Left"
                return True  # 成長した
            elif self.balance == "Left":
                if self.left.balance == "Right":
                    self.replace(p, self.DoubleRightRotation())
                elif self.left.balance == "Left":
                    self.replace(p, self.SingleRightRotation())
                return False  # rotationを行うと成長しない
        if self.key < key:
            if self.right is None:
                self.right = Avltree(key)
            else:
                if not self.right.insertx(self, key):
                    return False
            if self.balance == "Left":
                self.balance = "Even"
                return False
            elif self.balance == "Even":
                self.balance = "Right"
                return True
            elif self.balance == "Right":
                if self.right.balance == "Left":
                    self.replace(p, self.DoubleLeftRotation())
                elif self.right.balance == "Right":
                    self.replace(p, self.SingleLeftRotation())
                return False
        return False  # self.key == key の時は何もしないので成長もしない

    def to_s(self):
        return self.key
    def left_s(self):
        if self.left is None:
            return None
        return (self.left).key
    def right_s(self):
        if self.right is None:
            return None
        return (self.right).key

def main():
    N = ii()
    P = lmi()
    L = []
    for i in range(N):
        L.append((P[i], i))
    L.sort(key=itemgetter(0), reverse=True)
    # print(L)
    ans = 0
    rb = Avltree()
    for x, i in L:
        rb.insert(i)
        l1 = rb.search_lower(i, -1)
        l2 = rb.search_lower(l1, -1)
        r1 = rb.search_higher(i, N)
        r2 = rb.search_higher(r1, N)
        # print(l2, l1, r1, r2)
        ans += (abs(i - l1) * abs(r2 - r1) + abs(l1 - l2) * abs(r1 - i)) * x
    print(ans)
    return





if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from bisect import *

input=sys.stdin.readline

def main():
    n = int(input()[:-1])
    aa = list(map(int, input().split()))
    ans = 0
    pos = [0] * n
    for i, a in enumerate(aa):
        pos[a - 1] = i
    # print(pos)
    fin = [-1, -1, n, n]
    for a in range(n - 1, -1, -1):
        i = pos[a]
        j = bisect_left(fin, i)
        fin.insert(j, i)
        ans += (a + 1) * ((fin[j - 1] - fin[j - 2]) * (fin[j + 1] - fin[j])
                          + (fin[j] - fin[j - 1]) * (fin[j + 2] - fin[j + 1]))
        # print(a, ans, fin)
    print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
from bisect import *

def main():
    n = int(input())
    aa = list(map(int, input().split()))
    ans = 0
    pos = [0] * n
    for i, a in enumerate(aa):
        pos[a - 1] = i
    #print(pos)
    fin = [-1, -1, n, n]
    for a in range(n - 1, -1, -1):
        i = pos[a]
        j = bisect_left(fin, i)
        fin.insert(j, i)
        ans += (a + 1) * ((fin[j - 1] - fin[j - 2]) * (fin[j + 1] - fin[j])
                          + (fin[j] - fin[j - 1]) * (fin[j + 2] - fin[j + 1]))
        # print(a, ans, fin)
    print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
*p, = map(int,input().split())

ans = 0
for i in range(n-1):
    for j in range(n)[i+1:]:
        ans += sorted(p[i:j+1])[-2]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python
# coding: UTF-8

#import scipy.optimize
import numpy as np



##################################################################
if __name__ == "__main__":
    Input = [input() for i in range(2)]
    N = int(Input[0])
    P = list(map(int,Input[1].split()))
    
    iPs = [0] * (N+1)
    for iP, A in enumerate(P):
        iPs[A] = iP
        #iPs[A]はPにAが入ってるインデックス

    ANS = 0
    uPi = [iPs[N]]
    for i in np.arange(N-1,0,-1):
        Si = [-1,-1]

        iP = iPs[i] #今回比較するPのインデックス

        arruPi = np.array(uPi)
        whiP = arruPi < iP
        Si.extend(list(arruPi[whiP])) #iPより小さいインデックスで、iより大きいPのインデックスをSiに追加
        Ti = list(arruPi[~whiP]) #iPより大きいインデックスで、iより大きいPのインデックスをTiに追加
        Ti.extend([N,N])
                  
        omega = Si[-2]
        x = Si[-1]
        y = Ti[0]
        z = Ti[1]
        
        ANS += i*((y-iP)*(x-omega)+(iP-x)*(z-y))
        
        uPi.extend([iP])
        uPi.sort()
    print(ANS)

Submission status: Time Limit Exceeded

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

ans = 0
for i in range(n-1):
    largest = p[i]
    sec_large = 0
    for j in range(i+1, n):
        if p[j] > largest:
##            print(f'X{i+1}{j+1}: {largest}')
            ans += largest
            sec_large = largest
            largest = p[j]
        else:
            sec_large = max(sec_large, p[j])
##            print(f'X{i+1}{j+1}: {sec_large}')
            ans += sec_large

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python
# coding: UTF-8

#import scipy.optimize
import numpy as np



##################################################################
if __name__ == "__main__":
    Input = [input() for i in range(2)]
    N = int(Input[0])
    P = list(map(int,Input[1].split()))
    
    iPs = [0] * (N+1)
    for iP, A in enumerate(P):
        iPs[A] = iP
        #iPs[A]はPにAが入ってるインデックス

    ANS = 0
    uPi = set([iPs[N]])
    for i in np.arange(N-1,0,-1):
        Si = set([-1])
        Ti = set([N])

        iP = iPs[i] #今回比較するPのインデックス
        Si_set = set(list(range(iP)))
        Si = Si | (Si_set & uPi) #iPより小さいインデックスで、iより大きいPのインデックスをSiに追加
        Ti = Ti | (uPi - Si) #iPより大きいインデックスで、iより大きいPのインデックスをTiに追加

        Si = sorted(list(Si))
        Ti = sorted(list(Ti))
        if len(Si) == 1:
            Si = [-1]+Si
        if len(Ti) == 1:
            Ti.append(N) 
        omega = Si[-2]
        x = Si[-1]
        y = Ti[0]
        z = Ti[1]
        
        ANS += i*((y-iP)*(x-omega)+(iP-x)*(z-y))
        
        uPi.add(iP)
    print(ANS)

Submission status: Time Limit Exceeded

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

m = 0
for i in range(n):
    for j in range(i+1,n):
        q = sorted(p[i:j+1], reverse=True)
        m+=q[1]

print(m)

Submission status: Time Limit Exceeded

Solution code:
import sys

def main():

	input = sys.stdin.readline

	N = int(input().strip())
	P = list(map(int,input().strip().split()))

	ips = [0]*(N)
	for i, val in enumerate(P):
		ips[val-1] = i
	P.sort(reverse=True)

	x = 0
	largeind = [-1,-1,N,N]
	for i in range(N):
		target = ips[P[i]-1]

		largeind.append(target)
		largeind.sort(reverse=True)
		ti = largeind.index(target)

		L1ind = largeind[ti-1]
		L2ind = largeind[ti-2]
		R1ind = largeind[ti+1]
		R2ind = largeind[ti+2]

		x += ((L1ind-L2ind)*(R1ind-target) + (target-L1ind)*(R2ind-R1ind))*P[i]

	print(x)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
p=list(map(int,input().split()))
ans=0
for i in range(n-1):
  for j in range(i+1,n):
    temp=sorted(p[i:j+1])
    ans+=temp[-2]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def second_max(arr):
    return [i for i in reversed(sorted(arr))][1]


def second_min(arr):
    return sorted(arr)[1]


N = int(input())

P = list(map(int, input().split()))

C = [-1, -1, N, N]


C.append(P.index(N))
result = 0
for i in reversed(range(1, N)):

    P_i = P.index(i)

    T = [j for j in C if j > P_i]
    S = [j for j in C if j < P_i]

    # get two minimum value w_i, x_i in T
    y_i = min(T)
    z_i = second_min(T)

    # get two max value in S
    x_i = max(S)
    w_i = second_max(S)

    C_i = (x_i - w_i)*(y_i - P_i) + (P_i - x_i) * (z_i - y_i)
    C.append(P_i)

    result += C_i * i

print(result)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

def main():

	input = sys.stdin.readline

	N = int(input().strip())
	P = np.array(list(map(int,input().strip().split())))

	ips = np.argsort(P)[::-1]
	psort = np.sort(P)[::-1]

	x = 0
	largeind = [-1,-1,N,N]
	for i in range(N):
		target = ips[i]

		larger = len(largeind)-2
		smaller = 1
		while larger-smaller!=1:
			medium = int((larger+smaller)/2)
			if largeind[medium]>target:
				larger = medium
			else:
				smaller = medium
		largeind.insert(larger,target)

		L1ind = largeind[larger-1]
		L2ind = largeind[larger-2]
		R1ind = largeind[larger+1]
		R2ind = largeind[larger+2]

		x += ((L1ind-L2ind)*(R1ind-target) + (target-L1ind)*(R2ind-R1ind))*psort[i]

	print(x)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:

from collections import deque, defaultdict
import copy
import bisect
#sys.setrecursionlimit(10 ** 9)
import math
import heapq

import sys
def input():
	return sys.stdin.readline().strip()


N = int(input())
P = list(map(int, input().split()))

zyun = [0]*N

for i in range(N):
	zyun[P[i] - 1] = i

A = [zyun[-1]]


total = 0
for i in range(N - 2, -1, -1):
	loc = bisect.bisect(A, zyun[i])
	bisect.insort(A, zyun[i])
	loc_before = [-1, -1]
	loc_after = [N, N]
	if loc > 0:
		loc_before[1] = A[loc - 1]
		if loc > 1:
			loc_before[0] = A[loc - 2]
	if loc < len(A) - 1:
		loc_after[0] = A[loc + 1]
		if loc < len(A) - 2:
			loc_after[1] = A[loc + 2]
	num = (loc_before[1]-loc_before[0])*(loc_after[0] - A[loc])
	#print(A[loc], loc_before, loc_after)
	num += (loc_after[1]-loc_after[0])*(A[loc] - loc_before[1])
	total += num*(i+1)
print(total)

Submission status: Time Limit Exceeded

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

dic = {}
for i in range(n):
    dic[p[i]] = i+1
    
ans = 0
big = {0,n+1}
big.add(dic[n])
for i in range(n-1,0,-1):
    i_no = dic[i]
    bigger = big & set(range(i_no+1,n+2,1))
    smaller = big & set(range(i_no-1,-1,-1))

    if len(bigger)==1:
        r1 = n+1
        r2 = n+1
    else:
        r1 = min(bigger)
        bigger.discard(r1)
        r2 = min(bigger)

    if len(smaller)==1:
        l1 = 0
        l2 = 0
    else:
        l1 = max(smaller)
        smaller.discard(l1)
        l2 = max(smaller)

    ans += i*((r2-r1)*(i_no-l1)+(r1-i_no)*(l1-l2))
    
    big.add(dic[i])
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
P = list(map(int,input().split()))

ans = 0
ta = 0
for i in range(N-1):
  m = min(P[i],P[i+1])
  M = max(P[i],P[i+1])  
  for j in range(i+1, N):
#    print (i, j, ":", m, M, "(",P[j],")" , ":",  end =" + ")
    tm = m
    TM = M
    ta = ans
    if j == i+1:
      ans += m
    elif P[j] > TM:
      ans += TM
      M = P[j]
      m = TM
    elif P[j] > tm:
      ans += P[j]
      m = P[j]
    else:
      ans += tm
#    print (ans-ta, "=", ans)
print (ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
P = list(map(int,input().split()))

L = []
ans = 0
for i in range(N-1):
  for j in range(i+1, N):
    L = P[i:j+1]
    ans += sorted(L)[-2]
print (ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
a = list(map(int,input().split()))
new=0
b=len(a)
while b>0:
    for i in range(len(a)-b):
        new+=sorted(a[i:i+b+1])[-2]
    b-=1
print(new)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
a = list(map(int,input().split()))
new=0
b=len(a)
for j in range(len(a)):
    for i in range(len(a)-b):
        new+=sorted(a[i:i+b+1])[-2]
    b-=1
print(new)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = list(map(int,input().split()))
a = 0

for l in range(n-1):
    for r in range(l+1,n):
        a += sorted(p[l:r+1])[-2]

print(a)

Submission status: Time Limit Exceeded

Solution code:
listA=[] #appendのために宣言が必要
while True:
    try:
        listA.append(list(map(int,input().split())))

    except:
        break;

a=listA[1]
new=0
b=len(a)
for j in range(len(a)):
    for i in range(len(a)-b):
        new+=sorted(a[i:i+b+1])[-2]
    b-=1
    
print(new)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python
# coding: UTF-8

#import scipy.optimize
#import numpy as np



##################################################################
if __name__ == "__main__":
    Input = [input() for i in range(2)]
    N = int(Input[0])
    P = list(map(int,Input[1].split()))
    
    iPs = [0] * (N+1)
    for iP, A in enumerate(P):
        iPs[A] = iP
        #iPs[A]はPにAが入ってるインデックス

    ANS = 0
    for L in range(N-1):
        R = N-1
        while R > L:
            B = P[L:R+1]
            MB = max(B)
            ind1 = iPs[MB]-L
            B.remove(MB)
            MB2 = max(B)
            ind2 = iPs[MB2]-L
            ind = max(ind1,ind2)
            ANS += MB2*(R+1-L-ind)
            R = L + ind -1
                #sP = sorted(P[L:R+1],reverse=True)
                #ans += sP[1]
    print(ANS)