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:
import time


class WeightBalancedTree:
    def __init__(self, q):
        self.left = [0] * (q + 1)
        self.right = [0] * (q + 1)
        self.weight = [1] * (q + 1)
        self.key = [None] * (q + 1)
        self.last_index = 0
        self.root = 0

# key 未満の最大値
    def search_lower(self, key):
        if key == None:
            return None
        ret = None
        idx = self.root
        while idx != 0:
            if self.key[idx] < key:
                ret = self.key[idx]
                idx = self.right[idx]
            else:
                idx = self.left[idx]
        return ret

# key 超過の最小値
    def search_higher(self, key):
        if key == None:
            return None
        ret = None
        idx = self.root
        while idx != 0:
            if self.key[idx] > key:
                ret = self.key[idx]
                idx = self.left[idx]
            else:
                idx = self.right[idx]
        return ret

# 要素の挿入
# 重複を考慮しない
# ToDo: 考慮するものも実装する
    def insert(self, key):
        self.last_index += 1
        self.key[self.last_index] = key
        self.weight[self.last_index] = 2
        self.root = self.__recursive_insert__(self.root)
        NotImplemented

# insert の再帰実装に用いる
    def __recursive_insert__(self, idx):
        if idx == 0:
            return self.last_index
        elif self.key[self.last_index] < self.key[idx]:
            self.left[idx] = self.__recursive_insert__(self.left[idx])
            self.__fix__(idx)
            return self.__fix_left_bias__(idx)
        else:
            self.right[idx] = self.__recursive_insert__(self.right[idx])
            self.__fix__(idx)
            return self.__fix_right_bias__(idx)

# ノードの weight を補正する
    def __fix__(self, idx):
        self.weight[idx] = self.weight[self.left[idx]] + \
            self.weight[self.right[idx]]

# 左回転
    def __rotate_left__(self, idx):
        right = self.right[idx]
        self.right[idx] = self.left[right]
        self.__fix__(idx)
        self.left[right] = idx
        self.__fix__(right)
        return right

# 右回転
    def __rotate_right__(self, idx):
        left = self.left[idx]
        self.left[idx] = self.right[left]
        self.__fix__(idx)
        self.right[left] = idx
        self.__fix__(left)
        return left

# 左偏状態の補正
    def __fix_left_bias__(self, idx):
        if self.weight[self.right[idx]] * 4 < self.weight[idx]:
            left = self.left[idx]
            if self.weight[self.left[left]] * 4 < self.weight[left]:
                self.left[idx] = self.__rotate_left__(left)
            idx = self.__rotate_right__(idx)
        return idx

# 右偏状態の補正
    def __fix_right_bias__(self, idx):
        if self.weight[self.left[idx]] * 4 < self.weight[idx]:
            right = self.right[idx]
            if self.weight[self.right[right]] * 4 < self.weight[right]:
                self.right[idx] = self.__rotate_right__(right)
            idx = self.__rotate_left__(idx)
        return idx

    def size(self):
        return self.weight[self.root] - 1

    def deb_print(self):
        self.__deb_print__(self.root, 0)

    def __deb_print__(self, idx, dep):
        if idx != 0:
            self.__deb_print__(self.right[idx], dep + 1)
            for _ in range(0, dep):
                print("   ", end="")
            print('i:{0},k:{1},l:{2},r:{3},w:{4}'.format(
                idx, self.key[idx], self.left[idx], self.right[idx], self.weight[idx]))
            self.__deb_print__(self.left[idx], 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])
    # print(idx)
    t = WeightBalancedTree(n+2)
    t.insert(-1)
    t.insert(n)
    ans = 0
    for i in idx:
        # print("")
        # print("")
        #print("begin tree")
        # t.deb_print()
        #print("end tree")
        #print('now size = {0}'.format(t.size()))
        #print('now i = {0}'.format(i))
        nex = t.search_higher(i)
        nexnex = t.search_higher(nex)
        pre = t.search_lower(i)
        prepre = t.search_lower(pre)
        #print([prepre, pre, nex, nexnex])
        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()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
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 random import shuffle
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 fi(): return float(input())
def mfi(): return map(float, input().rstrip().split())
def lmfi(): return list(map(float, 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

# BEGIN CUT HERE
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):
        node = self
        while node is not None:
            if node.key == key:
                return node  # node.key == keyの場合
            if node.key > key:
                node = node.left
            elif node.key < key:
                node = node.right
        return None

    def search_lower(self, key, key_lower):
        node = self
        if node.key is None:
            return key_lower
        ans = key_lower
        while node is not None:
            if node.key < key:
                if ans < node.key:
                    ans = node.key
                node = node.right
            elif node.key >= key:
                node = node.left
        return ans

    def search_higher(self, key, key_higher):
        node = self
        if node.key is None:
            return key_higher
        ans = key_higher
        while node is not None:
            if node.key > key:
                if ans > node.key:
                    ans = node.key
                node = node.left
            elif node.key <= key:
                node = node.right
        return ans


    def end_lower(self, end_lower_key):
        node = self
        while node.left is not None:
            node = node.left
        return node.key

    def end_higher(self, end_higher_key):
        node = self
        while node.right is not None:
            node = node.right
        return node.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
        node = self
        s = []
        while True:
            if node.key > key:
                s.append((node, -1))
                if node.left is None:
                    node.left = Avltree(key)
                    node = node.left
                    break
                else:
                    node = node.left
            elif node.key < key:
                s.append((node, 1))
                if node.right is None:
                    node.right = Avltree(key)
                    node = node.right
                    break
                else:
                    node = node.right
        while len(s) != 0:
            node, direct = s.pop()
            if len(s) != 0:
                par = s[-1][0]
            else:
                par = p
            if direct == -1:
                if node.balance == "Right":
                    node.balance = "Even"
                    break
                elif node.balance == "Even":
                    node.balance = "Left"
                elif node.balance == "Left":
                    if node.left.balance == "Right":
                        node.replace(par, node.DoubleRightRotation())
                    elif node.left.balance == "Left":
                        node.replace(par, node.SingleRightRotation())
                    break
            elif direct == 1:
                if node.balance == "Left":
                    node.balance = "Even"
                    break
                elif node.balance == "Even":
                    node.balance = "Right"
                elif node.balance == "Right":
                    if node.right.balance == "Left":
                        node.replace(par, node.DoubleLeftRotation())
                    elif node.right.balance == "Right":
                        node.replace(par, node.SingleLeftRotation())
                    break

    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
# END CUT HERE

def main():
    N = ii()
    P = lmi()
    L = [0 for i in range(N)]
    for i in range(N):
        L[P[i] - 1] = i
    L.reverse()
    # debug(L)
    ans = 0
    rb = Avltree()
    for num, i in enumerate(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)
        debug(l2, l1, r1, r2)
        ans += (abs(i - l1) * abs(r2 - r1) + abs(l1 - l2) * abs(r1 - i)) * (N - num)
    print(ans)


if __name__ == '__main__':
    if not __debug__:
        import doctest
        doctest.testmod()
        import cProfile
        cProfile.run('main()')
    else:
        main()

Submission status: Time Limit Exceeded

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

s = 0
for l in range(n - 1):
    r = l + 1
    second_max_, max_ = sorted(pl[l:r + 1])
    s += second_max_
    for r in range(l+2, n):
        if max_ <= pl[r]:
            second_max_ = max_
            max_ = pl[r]
        elif second_max_ < pl[r]:
            second_max_ = pl[r]
        s += second_max_
print(s)

Submission status: Time Limit Exceeded

Solution code:
import math
n = int(input()) 
a = [int(item) for item in input().split()]
q = []
for i, item in enumerate(a):
    q.append((item, i))
q.sort(reverse=True)

seen = [1] * 2 + [0] * n + [1] * 2
n += 4

bag_num = math.ceil(math.sqrt(n))
bag_size = (n + bag_num - 1) // bag_num
seen += [0] * (bag_num * bag_size - n)
bag = [0] * bag_num

for i, item in enumerate(seen):
    if item == 1:
        bag[i // bag_size] = 1

def add(k):
    seen[k] += 1
    bag[k // bag_size] = 1

def query_left(k):
    l = k - 1
    while l % bag_size > 0:
        if seen[l] == 1:
            return l
        l -= 1
    if seen[l] == 1:
        return l
    while bag[(l+1) // bag_size - 1] == 0:
        l -= bag_size
    while seen[l] == 0:
        l -= 1
    return l

def query_right(k):
    r = k + 1
    while r % bag_size < bag_size - 1:
        if seen[r] == 1:
            return r
        r += 1
    if seen[r] == 1:
        return r
    while bag[r // bag_size + 1] == 0:
        r += bag_size
    while seen[r] == 0:
        r += 1
    return r

ans = 0
for item, idx in q:
    # print(seen)
    idx += 2
    # print(idx)
    l1 = query_left(idx)
    l2 = query_left(l1)
    r1 = query_right(idx)
    r2 = query_right(r1)
    if l2 == 0 and l1 == 1:
        l2 = l1
    if r2 == n-1 and r1 == n-2:
        r2 = r1
    # print(l2, l1, idx, r1, r2)
    ans += (l1 - l2) * (r1 - idx) * item
    ans += (idx - l1) * (r2 - r1) * item
    # print(ans)
    add(idx)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

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

    li = [True] * n
    q = sorted(p,reverse = True)
    ans = 0

    for i in range(n):
        q1 = q[i]
        label = p.index(q1)
        li[label] = False
        a = label+1
        b = label-1
        count1 = 1
        count2 = 0
        count3 = 1
        count4 = 0
        while a < n:
            if li[a]:
                count1 += 1
                a += 1
            else:
                break
        if a != n:
            a += 1
            count2 += 1
        while a < n:
            if li[a]:
                count2 += 1
                a += 1
            else:
                break
        while b >= 0:
            if li[b]:
                count3 += 1
                b -= 1
            else:
                break
        if b != -1:
            b -= 1
            count4 += 1
        while b >= 0:
            if li[b]:
                count4 += 1
                b -= 1
            else:
                break
        ans += q1 * (count1 * count4 + count2 * count3)

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n = int(input())
p = tuple(map(int,input().split()))
ans = 0
si = list(p)

for i in range(n):
    for j in range(n):
        si[j] = np.sign( p[i] -p[j] )
    s = [0]+si+[0]
    i += 1
    
    count = 0
    sign = 1
    while sign == 1:
        count += 1
        sign *= int(s[i+ count])
    p1 = count
    while sign == -1:
        count += 1
        sign *= int(s[i+ count])
    p2 = count

    count = 0
    sign = 1
    while sign == 1:
        count += 1
        sign *= int(s[i- count])
    m1 = count
    while sign == -1:
        count += 1
        sign *= int(s[i- count])
    m2 = count

    ans += p[i-1]*(m1*(p2-p1) + (m2-m1)*p1)

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
from random import shuffle
import cProfile
sys.setrecursionlimit(200000)
# local only
# if not __debug__:
#     fin = open('text.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

# BEGIN CUT HERE
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):
        node = self
        while node is not None:
            if node.key == key:
                return node  # node.key == keyの場合
            if node.key > key:
                node = node.left
            elif node.key < key:
                node = node.right
        return None

    def search_lower(self, key, key_lower):
        node = self
        if node.key is None:
            return key_lower
        ans = key_lower
        while node is not None:
            if node.key < key:
                if ans < node.key:
                    ans = node.key
                node = node.right
            elif node.key >= key:
                node = node.left
        return ans

    def search_higher(self, key, key_higher):
        node = self
        if node.key is None:
            return key_higher
        ans = key_higher
        while node is not None:
            if node.key > key:
                if ans > node.key:
                    ans = node.key
                node = node.left
            elif node.key <= key:
                node = node.right
        return ans


    def end_lower(self, end_lower_key):
        node = self
        while node.left is not None:
            node = node.left
        return node.key

    def end_higher(self, end_higher_key):
        node = self
        while node.right is not None:
            node = node.right
        return node.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
        node = self
        s = []
        while True:
            if node.key > key:
                s.append((node, -1))
                if node.left is None:
                    node.left = Avltree(key)
                    break
                else:
                    node = node.left
            elif node.key < key:
                s.append((node, 1))
                if node.right is None:
                    node.right = Avltree(key)
                    break
                else:
                    node = node.right
        while len(s) != 0:
            p, direct = s.pop()
            if direct == -1:
                if node.balance == "Right":
                    node.balance = "Even"
                    break
                elif node.balance == "Even":
                    node.balance = "Left"
                elif node.balance == "Left":
                    if node.left.balance == "Right":
                        node.replace(p, node.DoubleRightRotation())
                    elif node.left.balance == "Left":
                        node.replace(p, node.SingleRightRotation())
                    break
            elif direct == 1:
                if node.balance == "Left":
                    node.balance = "Even"
                    break
                elif node.balance == "Even":
                    node.balance = "Right"
                elif node.balance == "Right":
                    if node.right.balance == "Left":
                        node.replace(p, node.DoubleLeftRotation())
                    elif node.right.balance == "Right":
                        node.replace(p, node.SingleLeftRotation())
                    break
            node = p

    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 bin_tree_to_list(root):
    """
    type root: root class
    """
    if not root:
        return root
    root = bin_tree_to_list_util(root)
    while root.left:
        root = root.left
    return root

def bin_tree_to_list_util(root):
    if not root:
        return root
    if root.left:
        left = bin_tree_to_list_util(root.left)
        while left.right:
            left = left.right
        left.right = root
        root.left = left
    if root.right:
        right = bin_tree_to_list_util(root.right)
        while right.left:
            right = right.left
        right.left = root
        root.right = right
    return root

def print_tree(root):
    while root:
        print(root.key)
        root = root.right

def binary_tree_paths(root):
    res = []
    if root is None:
        return res
    dfs(res, root, str(root.key))
    return res

def dfs(res, root, cur):
    if root.left is None and root.right is None:
        res.append(cur)
    if root.left:
        dfs(res, root.left, cur + '->' + str(root.left.key))
    if root.right:
        dfs(res, root.right, cur + '->' + str(root.right.key))
# END CUT HERE



def main():
    N = ii()
    P = lmi()
    L = [0 for i in range(N)]
    for i in range(N):
        L[P[i] - 1] = i
    L.reverse()
    ans = 0
    rb = Avltree()
    for num, i in enumerate(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)
        # debug(l2, l1, r1, r2)
        ans += (abs(i - l1) * abs(r2 - r1) + abs(l1 - l2) * abs(r1 - i)) * (N - num)
    print(ans)
    # print(rb.inorder())
    return



if __name__ == '__main__':
    # cProfile.run('main()')
    main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n = int(input())
p = [int(num) for num in input().split(" ")]

total = 0

for i in range(n-1):
    for j in range(i+1, n):
        x = np.sort(np.array(p[i:j+1]))
        total += x[len(x)-2]
print(total)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())

ans=0
temp=0
second_Biggest=0

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

for x in range(n):
    sortlis = sorted(lis[x:])
    second_Biggest = sortlis[n-x-2]
    biggest = sortlis[n-x-1]
    #print("The second biggest is {}".format(second_Biggest))
    for y in range(x+1,n):
        
        templist = lis[x:y+1]
        #print("looking at {}".format(templist))
        if second_Biggest in templist and biggest in templist:
            #print("{} added".format(second_Biggest*(n-y)))
            ans+=second_Biggest*(n-y)
            break
        else:
            temp=sorted(templist)[-2]
            ans+=temp

#print("tried {} times".format(count))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())

ans=0
temp=0
second_Biggest=0
count=0
lis=(list(map(int,input().split())))

for x in range(n):
    sortlis=sorted(lis[x:])
    second_Biggest = sortlis[n-x-2]
    #print("The second biggest is {}".format(second_Biggest))
    for y in range(x+1,n):
        templis=lis[x:y+1]
        temp=sorted(templis)[-2]
        count+=1
        if(temp==second_Biggest):
            ans+=temp*(n-y)
            break
        else:
            ans+=temp

#print("tried {} times".format(count))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect

N = int(input())
P = [0] + list(map(int,input().split()))
I = [0] * (N+1)

for j in range(1,N+1):
    I[P[j]] = j

#print(I)

C = [0] * (N+1)
l = [0,0,N+1,N+1]

for i in range(N,0,-1):
    k = bisect.bisect_left(l,I[i])
    S = l[:k]
    T = l[k:]
    w = S[-2]
    x = S[-1]
    y = T[0]
    z = T[1]
    C[i] = (x-w) * (y-I[i]) + (I[i]-x) * (z-y)
    l = S + [I[i]] + T
    #print(i,C[i],l)

total = 0
for j in range(1,N+1):
    total += j * C[j]

print(total)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N = int(input())
P = [ int(n) for n in input().split() ]

I = np.argsort(P)[::-1]

w = [ -1 for _ in range(N)]
x = [ -1 for _ in range(N)]
y = [ N  for _ in range(N)]
z = [ N  for _ in range(N)]
    
for j in range(N):
    p = I[j]
    for q in range(w[p]+1, x[p]):
        z[q] = p
    for q in range(x[p]+1, p):
        z[q] = y[q]
        y[q] = p
    for q in range(p+1, y[p]):
        w[q] = x[q]
        x[q] = p
    for q in range(y[p]+1, z[p]):
        w[q] = p

sum = 0
for i in range(N):
    sum += P[i] * ( (x[i]-w[i])*(y[i]-i) + (i-x[i])*(z[i]-y[i]) )
    # w[i] < L <= x[i] and    i <= R < y[i]
    # or
    # x[i] < L <= i    and y[i] <= R < z[i]
        
print(sum)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())

ans=0

lis=(list(map(int,input().split())))
#print(lis)

for x in range(n):
    for y in range(x+1,n):
        templis=lis[x:y+1]
        #print(sorted(templis))
        ans+=sorted(templis)[-2]

print(ans)

Submission status: Time Limit Exceeded

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

ANS=0
for l in range(0, N-1):
  for r in range(l+1, N):
    ANS+=sorted(P[l:r+1])[-2]
    
print(ANS)

Submission status: Time Limit Exceeded

Solution code:
#
n = int(input())
p = list(map(int,input().split()))
#
s = 0
for l in range(0,n-1):
    if p[l]<p[l+1]:
        x1 = p[l+1]
        x2 = p[l]
    else:
        x1 = p[l]
        x2 = p[l+1]
    s = s + x2

    if l == n-2:
        break

    for r in range(l+2,n):
        if p[r] > x2:
            if p[r] < x1:
                x2 = p[r]
            else:
                x2 = x1
                x1 = p[r]
        s = s + x2

print(s)

Submission status: Time Limit Exceeded

Solution code:
#
n = int(input())
p = list(map(int,input().split()))
#
s = 0
for l in range(0,n-1):
    if p[l]<p[l+1]:
        x1 = p[l+1]
        x2 = p[l]
    else:
        x1 = p[l]
        x2 = p[l+1]
    s = s + x2

    if l == n-2:
        break

    for r in range(l+2,n):
        if p[r] > x1:
            x2 = x1
            x1 = p[r]
        elif x2 < p[r] and p[r] < x1:
            x2 = p[r]
        s = s + x2

print(s)

Submission status: Time Limit Exceeded

Solution code:
import bisect

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

# index list
lst = [0] * (N + 1)
for i in range(N):
    lst[P[i]] = i

finished = [-1, -1, lst[N], N, N] # index set
#print(finished)
ans = 0
for i in range(N - 1, 0, -1):
    idx = lst[i]
    idx2 = bisect.bisect_left(finished, idx)
    finished = finished[:idx2] + [idx] + finished[idx2:]
    #print(finished)
    x = finished[idx2 - 1]
    y = finished[idx2 + 1]
    z = finished[idx2 + 2]
    w = finished[idx2 - 2]
    #print('When P_i = {}, w={}, x={}, y={}, z={}'.format(i,w,x,y,z))

    C = (x - w) * (y - idx) + (idx - x) * (z - y)
    ans += i * C
    #print('ans = {}'.format(ans))

print(ans)