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 numpy as np

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

result=0
for i in range(N):
    countnum=N-1-i
    for j in range(countnum):
        Q=P[i:i+j+2]   
        sort=np.argsort(Q)[-2]
        #print(sort)
        result+=Q[sort]
        #print(result)
print(result)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = list(map(int, input().split()))
res = 0
for i in range(n):
  if p[i] == n:
    continue
  ll = -1
  lr = -1
  rl = n
  rr = n
  flag = 0
  for j in range(i - 1, -1, -1):
    if flag == 2:
      break
    if p[j] > p[i]:
      if flag == 0:
        lr = j
      else:
        ll = j
      flag += 1
  flag = 0
  for j in range(i + 1, n):
    if flag == 2:
      break
    if p[j] > p[i]:
      if flag == 0:
        rl = j
      else:
        rr = j
      flag += 1
  res += p[i] * ((i - lr) * (rr - rl) + (rl - i) * (lr - ll))
print(res)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7)

n=int(input())
b=input().split()
for i in range(n):
    b[i]=int(b[i])

def main(l,m1,m2,c,s):
    c+=1
    #print(m1,m2,s,c)
    while c<n-l:
        if c==1:
            m1=max(b[l],b[l+1])
            m2=min(b[l],b[l+1])
            s+=m2
            c+=1
            #print(m1,m2,s,c)
        elif b[l+c]>m1:
            m2=m1
            m1=b[l+c]
            s+=m2
            c+=1
        elif b[l+c]>m2:
            m2=b[l+c]
            s+=m2
            c+=1
        else:
            s+=m2
            c+=1
    return s
s1=0
for i in range(n-1):
    s=main(i,0,0,0,0)
    #print(s)
    s1+=s
    #print(s,s1)
print(s1)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
N = int(input())
P_list = list(map(int, input().split()))

# rev_P_list = []
# for P in (reversed(P_list)):
#     rev_P_list.append(P)

x_dic = {}
ans = 0
for i in range(N - 1):
    for j in range(i + 1, N):
        if j == i + 1:
            x_dic["{}_{}".format(i, j)] = sorted([P_list[i], P_list[j]], reverse=True)
            ans += x_dic["{}_{}".format(i, j)][1]
        else:
            tmp_list = [t for t in x_dic["{}_{}".format(i, j - 1)]]
            tmp_list.append(P_list[j])
            tmp_list = sorted(tmp_list, reverse=True)
            x_dic["{}_{}".format(i, j)] = [tmp_list[0], tmp_list[1]]
            ans += x_dic["{}_{}".format(i, j)][1]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!

from collections import deque

N = int(input())
P = deque(list(map(int,input().split())))
tmp = 0
most_max = 0
next_max = 0
ctr = 0

for i in range(N):
    most_max = P.popleft()
    for j in range(len(P)):
        if P[j] > most_max:
            next_max = most_max
            most_max = P[j]
        elif P[j] > next_max:
            next_max = P[j]
        ctr += next_max
    most_max = 0
    next_max = 0
        
print(ctr)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
P = [int(i) for i in input().split()]

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

print(result)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = list(map(int, input().split()))
summantion = 0
minlist = []

for i in range(n - 1):
    minlist2 = minlist
    minlist = []
    if i == 0:
        for j in range(n - 1 - i):
            a = p[j]
            b = p[j + 1]
            minlist.append([a, b] if a > b else [b, a])
            summantion = summantion + min(a, b)
    else:
        for j in range(n - 1 - i):
            if minlist2[j][0] == minlist2[j + 1][0]:
                a = minlist2[j][0]
                b = max(minlist2[j][1], minlist2[j + 1][1])
            else:
                a = max(minlist2[j][0], minlist2[j + 1][0])
                b = min(minlist2[j][0], minlist2[j + 1][0])

            minlist.append([a, b])
            summantion = summantion + b
print(summantion)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

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

ans =0

for i in range(n-1):
   for j in range(n-1-i):
      c =blist[i:i+j+2]
      ans += sorted(c)[-2]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def A():
    print(int(input())**3)

def B():
    N = int(input())
    A = [int(i) for i in input().split()]
    B = [int(i) for i in input().split()]
    C = [int(i) for i in input().split()]

    points = B[A[0]-1]
    previous = A[0]-1
    #print(points)
    for i in range(1, N):
        points += B[A[i]-1]
        if A[i]-1 == previous+1:
            points += C[previous]
        #print(points)
        previous = A[i]-1
    
    print(points)

def C():
    N = int(input())
    B = [int(i) for i in input().split()]

    s = B[0]
    temp = B[0]
    for i in range(1, len(B)):
        if B[i] > temp:
            s += temp
        else:
            s += B[i]
        
        temp = B[i]
    
    s += temp

    print(s)

def E():
    N = int(input())
    P = [int(i) for i in input().split()]
    s = 0
    for i in range(N-1):
        for j in range(i+1, N):
            temp = P[i:j+1]
            del temp[temp.index(max(temp))]
            s += max(temp)
            if temp == N-1:
                s += temp*(N-(j+1))
                break
            
    print(s)

E()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = list(map(int,input().split()))
m = 0
for i in range(n-1):
    t = p
    for j in range(i+1,n):
        u = t[i:j+1]
        u.remove(max(t[i:j+1]))
        m += max(u)
print(m)

Submission status: Time Limit Exceeded

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

first, second = 0, 0
ans = 0
for i in range(0, N-1):
    first = max(P[i], P[i+1])
    second = min(P[i], P[i+1])
    ans += second
    if i<N-2:
        for j in range(i+2,N):
            new = P[j]
            if new > first:
                second = first
                first = new
            elif new < first and new > second:
                second = new
            else:
                pass
            ans += second

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = list(map(int, input().split()))
total = 0
for l in range(1,n):
    for r in range(l+1,n+1):
        total += sorted(p[l-1:r])[-2]
print(total)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
A=list(map(int,input().split()))
counter=0
while len(A)>1:
  f=max(A[0],A[1])
  s=min(A[0],A[1])
  counter+=s
  for i in range(len(A)-2):
    if f<A[i+2]:
      s=f
      f=A[i+2]
      
    elif s<A[i+2]:
      s=A[i+2]
      
    counter+=s
  A.pop(0)

print(counter)

Submission status: Time Limit Exceeded

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

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

print(SUM)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = list(map(int, input().split()))
dp = [[None]*(n) for _ in range(n-1)]
ans = 0

for i in range(n-1):
    for j in range(i+1, n):
        if i+1 == j:
            a, b = p[i], p[j]
            if a > b: a ,b = b, a
            dp[i][j] = (a, b)
            ans += a
        else:
            c = p[j]
            if dp[i][j-1][0] < c:
                if dp[i][j-1][1] < c:
                    dp[i][j] = (dp[i][j-1][1], c)
                else:
                    dp[i][j] = (c, dp[i][j-1][1])
            else:
                dp[i][j] = dp[i][j-1]
            ans += dp[i][j][0]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
def main():
    input = sys.stdin.readline
    N = int(input())
    P = list(map(int, input().split()))
    ans = 0
    for l in range(N-1):
        l += 1
        for r in np.arange(start=l+1, step=1, stop=N+1):
            #print(l,r)
            x_cand = P[l-1:r]
            #print(x_cand)
            x_sorted = np.sort(x_cand)
            #print(x_sorted)
            x_lr = x_sorted[-2]
            ans += x_lr

    print(ans)
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
ListP = [int(val) for val in input().split()]

l = 0
r = 2
xlr = 0
tempMax = temp2Max = 0
while (l < n - 1):
	temp2Max = min(ListP[l : l + 2])
	xlr += temp2Max
	tempMax = max(ListP[l : l + 2])
	while (r < n):
		if (temp2Max < ListP[r]):
			if (tempMax < ListP[r]):
				temp2Max = tempMax
				tempMax = ListP[r]
			else:
				temp2Max = ListP[r]
		xlr += temp2Max
		r += 1
	l += 1
	r = l + 2
print(xlr)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

n = int(stdin.readline().rstrip())
p_lst = [int(x) for x in stdin.readline().rstrip().split()]
cum = 0

def x_lr(l, r):
  return sorted(p_lst[l:r+1])[-2]

for l in range(n-1):
  for r in range(l+1, n):
    cum += x_lr(l, r)
    
print(cum)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
P = list(map(int,input().split()))
ans = 0
for i in range(N):
    for j in range(i+1,N):
        tmp = P[i:j+1]
        tmp.sort(reverse = True)
        ans += tmp[1]
print(ans)

Submission status: Time Limit Exceeded

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

def cal1(M, T, N):
    if M < N:
        return [N, M]
    elif N > T:
        return [M, N]
    else:
        return [M, T]

        
cnt = 0 
for i in range(N-1):
    if P[i] > P[i+1]:
        M = P[i]
        T = P[i+1]
    else:
        M = P[i+1]
        T = P[i]
    for j in range(i+1,N):
        if i +1 == j:
            cnt += T
        else:
            M,T =  cal1(M,T, P[j])
            cnt += T

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

#N = 8
#P = [8, 2, 7, 3, 4, 5, 6, 1]
N=int(input())  
P=list(map(int, input().split())) 
#L = 0
X = 0

for L in range(N-1):
    for R in range(L+1, N):
        a = np.array(P[L:R+1])
        #print(np.sort(a))
        #print(np.sort(a)[-2])
        Xi = np.sort(a)[-2]
        X += Xi
print(X)

Submission status: Time Limit Exceeded

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

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

print(count)

Submission status: Time Limit Exceeded

Solution code:
import itertools

N = int(input())
NL = list(itertools.combinations(list(range(1,N+1)),2))
P = list(map(int,input().split()))
ans = 0

for i in range(len(NL)):
    PS = P[NL[i][0]-1:NL[i][1]]
    PS.sort()
    ans += PS[-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(n-1):
    if p[l]>p[l+1]:
        pre1st,pre2nd=p[l],p[l+1]
    else:
        pre1st,pre2nd=p[l+1],p[l]
    ans+=pre2nd
    for r in range(l+2,n):
        if pre1st<p[r]:
            pre1st,pre2nd=p[r],pre1st
        else:
            if pre2nd<p[r]:
                pre2nd=p[r]
        ans+=pre2nd

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
P = [int(i) for i in input().split()]
ans = 0
for l in range(N):
    for r in range(l+1,N):
        ans+=sorted(P[l:r+1],reverse=True)[1]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = list(map(int,input().split()))
m = []
for i in range(n-1):
    t = p
    for j in range(i+1,n):
        u = t[i:j+1]
        u.remove(max(t[i:j+1]))
        m.append(max(u))

print(sum(m))

Submission status: Time Limit Exceeded

Solution code:
import sys

def main():
    N,*P = map(int, open(0).read().split())

    ans = 0
    for l in range(N-1):
        if P[l] > P[l+1]:
            ma = P[l]
            sma = P[l+1]
        else:
            ma = P[l+1]
            sma = P[l]
        ans += sma
        for r in range(l+2,N):
            if P[r] > ma:
                sma = ma
                ma = P[r]
            elif P[r] > sma:
                sma = P[r]
            ans += sma
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

for l in range(n-1):
  for r in range(l+1, n):
    p_copy = p[l:r+1]
    p_copy.remove(max(p_copy))
    c += max(p_copy)
    
print(c)

Submission status: Time Limit Exceeded

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

sum = 0
for i in range(len(list_p)-1):
  for j in range(i+1, len(list_p)):
    list_temp = list_p[i:j+1]
    sum += sorted(list_temp)[-2]

print(sum)

Submission status: Time Limit Exceeded

Solution code:
n = int(input(''))
p = [int(x) for x in str(input('')).split(' ')]
total = 0

for l in range (0, len(p)-1):
    for r in range (l+1, len(p)):
        subs = p[l: r+1]
        subs.sort()
        total += subs[-2]
        
print(total)

Submission status: Time Limit Exceeded

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

def main():
    N = int(input())
    P = list(map(int, input().split()))
    ans = 0
    for l in range(N-1):
        for r in range(l+1,N):
            p = P[l:r+1]
            p.sort(reverse=True)
#            print(l,r,p)
            ans += p[1]
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
n = int(input())
p = list(map(int, input().split()))
sum = 0
for L in range(1,n):
  for R in range(L+1,n+1):
    tmp = p[L-1:R]
    tmp.sort(reverse=True)
    sum += tmp[1]

print(sum)

Submission status: Time Limit Exceeded

Solution code:
def solve():
    data = read()
    result = think(data)
    write(result)


def read():
    n = read_int(1)[0]
    return read_int(n)


def read_int(n):
    return list(map(lambda x: int(x), read_line().split(' ')))[:n]


def read_float(n):
    return list(map(lambda x: float(x), read_line().split(' ')))[:n]


def read_line(n=0):
    if n == 0:
        return input().rstrip()
    else:
        return input().rstrip()[:n]


def think(data):
    n = len(data)
    dp1 = [[0 for x in range(n)] for y in range(n)]
    dp2 = [[0 for x in range(n)] for y in range(n)]

    # dp1[left][right] is maximum value about pair(L, R)
    # dp2[left][right] is second maximum value about pair(L, R)

    for i in range(n - 1):
        dp1[i][i + 1] = max(data[i], data[i + 1])
        dp2[i][i + 1] = min(data[i], data[i + 1])

    for left in range(0, n - 1):
        for right in range(left + 2, n):
            if dp2[left][right - 1] > data[right]:
                dp2[left][right] = dp2[left][right - 1]
                dp1[left][right] = dp1[left][right - 1]
            else:
                if dp1[left][right - 1] <= data[right]:
                    dp2[left][right] = dp1[left][right - 1]
                    dp1[left][right] = data[right]
                else:
                    dp1[left][right] = dp1[left][right - 1]
                    dp2[left][right] = data[right]

    total = 0
    for y in range(n):
        total += sum(dp2[y])
    return total


def write(result):
    print(result)


if __name__ == '__main__':
    # import doctest
    # doctest.testmod()
    # import sys
    # sys.setrecursionlimit(10000)
    solve()

Submission status: Time Limit Exceeded

Solution code:
import heapq
N = int(input())
P = list(map(int,input().split()))
sum = 0
heap = []
for L in range(N-1):
    heapq.heappush(heap,-(P[L]))
    for R in range(L+1,N):
        heapq.heappush(heap,-(P[R]))
        heap.sort()
        sum -= heap[1]
    heap = []
print(sum)

Submission status: Time Limit Exceeded

Solution code:
import bisect

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

count = 0
for i in range(N-1):
    can_use = sorted(P[i:i+1])
    for j in range(i+1, N):
        bisect.insort(can_use, P[j])
        can_use = can_use[-2:]
        count += can_use[-2]

print(count)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!

from collections import deque

N = int(input())
P = deque(list(map(int,input().split())))
tmp = 0
most_max = 0
next_max = 0
ctr = 0

for i in range(N):
    most_max = P.popleft()
    for j in range(len(P)):
        if P[j] > most_max:
            next_max = most_max
            most_max = P[j]
        elif P[j] > next_max:
            next_max = P[j]
        ctr += next_max
    most_max = 0
    next_max = 0
        
print(ctr)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

combi = list(itertools.combinations(range(n), 2))
ans = 0

def second_max(ls):
    ls.sort()
    return ls[len(ls) - 2]

for i in range(len(combi)):
    ans += second_max(p[combi[i][0]:combi[i][1] + 1])

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):
	for j in  range(i+1, N):
		#print("i: {}, j:{}".format(i,j))
		tmp = P[i:j+1]
		ans += sorted(tmp)[-2]
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):
    target = p[i]
    a = -1
    b = -1
    c = n
    d = n
    flag = 0
    for j in range(i-1, -1, -1):
        if p[j] > target:
            b = j
            if b != 0:
                flag = 1
            break
    if flag == 1:
        for j in range(b-1, -1, -1):
            if p[j] > target:
                a = j
                break

    flag = 0
    for j in range(i+1, n):
        if p[j] > target:
            c = j
            if c != n-1:
                flag = 1
            break
    if flag == 1:
        for j in range(c+1, n):
            if p[j] > target:
                d = j
                break

    ans += (b-a)*(c-i)*target + (d-c)*(i-b)*target

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
N = int(input())
P_list = list(map(int, input().split()))

# rev_P_list = []
# for P in (reversed(P_list)):
#     rev_P_list.append(P)

x_list_list = [[0 for i in range(N)] for i in range(N)]
ans = 0
for i in range(N - 1):
    for j in range(i + 1, N):
        if j == i + 1:
            x_list_list[i][j] = sorted([P_list[i], P_list[j]], reverse=True)
            ans += x_list_list[i][j][1]
        else:
            tmp_list = [t for t in x_list_list[i][j - 1]]
            tmp_list.append(P_list[j])
            tmp_list = sorted(tmp_list, reverse=True)
            x_list_list[i][j] = [tmp_list[0], tmp_list[1]]
            ans += x_list_list[i][j][1]

print(ans)

Submission status: Time Limit Exceeded

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

res = 0
for li in range(N-1):
  for ri in range(li+1, N):
    first = 0
    second = 0
    for i in range(li, ri+1):
      p = P[i]
      if p > first:
        second = first
        first = p
      elif p > second:
        second = p
    res += second

print(res)

Submission status: Time Limit Exceeded

Solution code:
def second_max(arr):
    return sorted(arr)[-2]


N = int(input())

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

result = 0
for L in range(N-1):
    cache = 0
    for R in range(L+1, N):
        if cache > P[R]:
            result += cache
        else:
            cache = second_max(P[L:R+1])
            result += cache

print(result)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=[[0]*(N+1) for i in range(N+1)]
C=[[0]*(N+1) for i in range(N+1)]
for i in range(1,N):
    B[i][i+1]=min(A[i],A[i-1])
    C[i][i+1]=max(A[i],A[i-1])
for i in range(1,N):
    for j in range(i+2,N+1):    
        if A[j-1]>C[i][j-1]:
            B[i][j]=C[i][j-1]
            C[i][j]=A[j-1]
        elif A[j-1]>B[i][j-1]:
            B[i][j]=A[j-1]
            C[i][j]=C[i][j-1]
        else:
            B[i][j]=B[i][j-1]
            C[i][j]=C[i][j-1]
total = 0
for i in B:
    total += sum(i)
print(total)

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:
n = int(input())
P = list(map(int, input().split()))

result = 0

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

Submission status: Time Limit Exceeded

Solution code:
def main():

    N = int(input())
    P = list(map(int, input().split()))
    total = 0
    for i in range(N - 1):
        for j in range(i + 1, N):
            myList = P[i:j + 1]
            myList.remove(max(myList))
            mx = max(myList)
            total += mx
    print(total)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

for l in range(n-1):
    pre1st=max(p[l],p[l+1])
    pre2nd=min(p[l],p[l+1])
    ans+=pre2nd
    for r in range(l+2,n):
        if pre1st<p[r]:
            pre1st,pre2nd=p[r],pre1st
        else:
            if pre2nd<p[r]:
                pre2nd=p[r]
        ans+=pre2nd

print(ans)

Submission status: Time Limit Exceeded

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

from math import *
import os
import sys

#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()))

    ans = 0
    for L in range(N-1):
        for R in np.arange(L+1,N,1):
                A = P[L:R+1]
                M = max(A)
                A.remove(M)
                ans += max(A)
                #sP = sorted(P[L:R+1],reverse=True)
                #ans += sP[1]
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

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

import heapq
my_list = []
sum = 0
for i in range(N-1):
    for j in range(i+1, N):
        my_list = P[i:j+1]
        my_list = [-i for i in my_list]
        heapq.heapify(my_list)
        heapq.heappop(my_list)
        sum += -min(my_list)

print(sum)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
P = [int(x) for x in input().split(' ')]

ans = 0
for i in range(N-1):
    fir = P[i]
    sec = 0
    for j in range(i+1, N):
        if P[j] > fir:
            sec = fir
            fir = P[j]
        elif P[j] > sec:
            sec = P[j]
        ans += sec

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
P = [int(i) for i in input().split()]

sum = 0

cache = []
first = max(P[N - 1], P[N - 2])
second = min(P[N - 1], P[N - 2])
cache.append([first, second])

sum += second

for i in range(2, N):
  next_cache = []

  L = N - i - 1

  first = max(P[L], P[L + 1])
  second = min(P[L], P[L + 1])
  next_cache.append([first, second])

  sum += second

  for p in cache:
    first = p[0]
    second = p[1]
    if p[0] <= P[L]:
      first = P[L]
      second = p[0]
    elif p[0] > P[L] and p[1] <= P[L]:
      second = P[L]

    sum += second

    next_cache.append([first, second])
  
  cache = next_cache

print(sum)

Submission status: Time Limit Exceeded

Solution code:

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

ret=0

ma = max(p[:2])
se = min(p[:2])


for l in range(n):
  for r in range(l,n):
    #tmp = p[l:r]
    #print("lr", l,r)
    if r==l:
      ma = max(p[l:l+2])
      se = min(p[l:l+2])
      #print("hei",ma, se)
      continue
    #print(tmp, end="")
    
    if p[r] > ma:
      se = ma
      ma = p[r]
    elif ma> p[r] and p[r] > se:
      se = p[r]
    
    #print(se)
    ret += se
    
print(ret)

Submission status: Time Limit Exceeded

Solution code:
import sys

#+++++
		
def main():
	n = int(input())
	lpn = list(map(int, input().split()))
	
	ret=0

	for i,l in enumerate(lpn[:-1]):
		fm = l
		sm=-1
		#print(fm)
		for r in lpn[i+1:]:
			if r > sm:
				sm=r
			if sm > fm:
				fm,sm = sm,fm
			#print(i,fm,sm)
			ret+=sm
			
	print(ret)
	
	
#+++++


if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Time Limit Exceeded

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

for i in range(N):
    j = 1
    while i + j < N:
        sorted_p = sorted(P[i:i+j+1], reverse=True)
        result += sorted_p[1]
        j += 1

print(result)

Submission status: Time Limit Exceeded

Solution code:
import sys


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


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

total = 0
for l in range(0, n - 1):
    for r in range(l + 1, n):
        if l + 1 == r:
            if P[l] <= P[r]:
                top1, top2 = P[r], P[l]
            else:
                top1, top2 = P[l], P[r]
            total += top2
        else:
            if top1 <= P[r]:
                top2 = top1
                top1 = P[r]
            elif top2 <= P[r] < top1:
                top2 = P[r]
            else:
                pass
            total += top2
print(total)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
p=[int(x) for x in input().split()]
m=[0]*3
s=0
# largest: m[2], 2nd largest: m[1]
for L in range(0,n-1):
    m[2] = p[L]
    m[1] = 0
    m[0] = 0
    for R in range(L+1, n):
        if R == L+1:
            m[1] = p[R]
            m.sort()
            s += m[1]
        else:
            m[0] = p[R]
            m.sort()
            s += m[1]
print(s)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
P=list(map(int,input().split()))
ans=0
for i in range(n-1):
  a=max(P[i:i+2])
  b=min(P[i:i+2])
  ans+=b
  for j in range(n-i-2):
    if P[i+j+2]>a:
      b=a
      a=P[i+j+2]
    elif b<P[i+j+2]<a:
      b=P[i+j+2]
    ans+=b
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = input().split()
for i in range(n):
    p[i] = int(p[i])
lst=[]
ans=0
for i in range(n-1):
    for j in range(i+1,n):
        for k in range(i,j+1):
            lst.append(p[k])
        ans+=sorted(lst)[-2]
        lst.clear()

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):
    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 main():
    n = int(input())
    p_s = list(map(int, input().split(' ')))

    result = 0

    for l in range(n-1):
        first = max(p_s[l:l+2])
        second = min(p_s[l:l+2])

        result += second

        for r in range(l+2, n):

            if second < p_s[r] < first:
                second = p_s[r]
            elif first < p_s[r]:
                second = first
                first = p_s[r]
            
            result += second
    print(result)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
ps = [int(x) for x in input().split()]

res  = 0
for l in range(n):
  cur_max = -1
  cur_2ndmax = -1
  for r in range(l+1, n):
    if r - l == 1:
      if ps[l] > ps[r]:
        cur_2ndmax = ps[r]
        cur_max = ps[l]
      else:
        cur_2ndmax = ps[l]
        cur_max = ps[r]
    else:
      if cur_max < ps[r]:
        cur_2ndmax = cur_max
        cur_max = ps[r]
      elif cur_2ndmax < ps[r]:
        cur_2ndmax = ps[r]
    res += cur_2ndmax

print(res)

Submission status: Time Limit Exceeded

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

count = 0
for i in range(N-1):
    can_use = sorted(P[i:i+1])
    for j in range(i+1, N):
        can_use.append(P[j])
        can_use = sorted(can_use)[-2:]
        count += can_use[-2]

print(count)

Submission status: Time Limit Exceeded

Solution code:
# coding=utf-8

if __name__ == "__main__":
    N = int(input())
    P = list(map(int, input().split()))

    list_ = []

    for i in range(N):
        max_ = 0
        second_max = 0
        for now in P[i:]:
            if now > max_:
                max_, second_max = now, max_
            elif now > second_max:
                second_max = now
            list_.append(second_max)

    print(sum(list_))

Submission status: Time Limit Exceeded

Solution code:
N=int(input())

listA=list(map(int,input().split()))
#print(listA[0:5])

listN=[]
ans=0
for i in range (N):
	for j in range(i+1,N):
		listN=listA[i:j+1]
		listN.remove(max(listN))
		ans+=max(listN)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N = int(input())
A = list(map(int, input().split())) 

loop = N
P = np.array(A)



w_all = np.array([])
for j in range(loop-1):
    for i in range(loop-1):        
        if 2+i+j<=loop:
            P_v = P[j:2+i+j]
            d = np.max(P_v)
            P_v = np.delete(P_v,np.where(P_v == d))
            w =np.max(P_v)
            w_all = np.append(w_all,w)
        else:
            pass
        
print(int(w_all.sum()))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = list(map(int, input().split()))
res = 0
for i in range(n):
  ll = -1
  lr = -1
  rl = n
  rr = n
  flag = 0
  for j in range(i - 1, -1, -1):
    if flag == 2:
      break
    if p[j] > p[i]:
      if flag == 0:
        lr = j
      else:
        ll = j
      flag += 1
  flag = 0
  for j in range(i + 1, n):
    if flag == 2:
      break
    if p[j] > p[i]:
      if flag == 0:
        rl = j
      else:
        rr = j
      flag += 1
  res += p[i] * ((i - lr) * (rr - rl) + (rl - i) * (lr - ll))
print(res)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
P = list(map(int, input().split()))
result = 0
for L in range(0, N - 1):
  no1 = P[L]
  no2 = -1
  for R in range(L + 1, N):
    if P[R] >= no1:
      no2 = no1
      no1 = P[R]
    elif P[R] >= no2:
      no2 = P[R]
    #print(no2)
    result += no2
print(result)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
P=[0]+[int(i) for i in input().split()]
#print(P)
num=0
for L in range(1,N):
  for R in range(L+1,N+1):
    #print(L,R,P[L],P[R],sorted(P[L:R+1])[-2])
    num += sorted(P[L:R+1])[-2]
print(num)