Problem:


Score: 400 points

Problem Statement

Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.

The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.

When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.

What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?

Constraints

All values in input are integers.

2 \leq N \leq 2 \times 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the maximum total comfort the N players can get.

Sample Input 1

4
2 2 1 3

Sample Output 1

7

By arriving at the place in the order Player 4, 2, 1, 3, and cutting into the circle as shown in the figure, they can get the total comfort of 7.

They cannot get the total comfort greater than 7, so the answer is 7.

Sample Input 2

7
1 1 1 1 1 1 1

Sample Output 2

6



Sample input:
4
2 2 1 3


Sample output:
7

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = [int(i) for i in input().split()]
A.sort(reverse=True)

comf = 0
chair = [A[0],A[0]]
for i in range(1,N):
  maxC = 0
  maxComf = 0
  for j in range(len(chair)-1):
    if chair[j] <= chair[j+1]:
      if maxComf < chair[j]:
        maxComf = chair[j]
        maxC = j+1
    elif maxComf < chair[j+1]:
      maxComf = chair[j+1]
      maxC = j+1
  chair.insert(maxC,A[i])
  comf += maxComf
print(comf)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
conf = A.pop(A.index(max(A)))
B = [A.pop(A.index(max(A)))]
B = [B[0], B[0]]
for i in range(2, N):
    conf += max(B)
    idx = B.index(max(B))
    del B[idx]
    val = A.pop(A.index(max(A)))
    B.insert(idx, val)
    B.insert(idx, val)
print(conf)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = sorted(list(map(int, input().split())), reverse = True)
B = [A[1], A[1]]
conf = A[0]
for i in range(2, N):
    conf += max(B)
    idx = B.index(max(B))
    del B[idx]
    B.insert(idx, A[i])
    B.insert(idx, A[i])
print(conf)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = sorted(list(map(int, input().split())), reverse = True)
B = [A[0], A[1]]
conf = A[0]
for i in range(2, N):
    max, index = 0, 0
    for j in range(i - 1):
        if min(B[j], B[j + 1]) >= max:
            max = min(B[j], B[j + 1])
            index = j + 1
    if min(B[i - 1], B[0]) >= max:
        max = min(B[i - 1], B[0])
        index = i
    conf += max
    B.insert(index, A[i])
print(conf)

Submission status: Time Limit Exceeded

Solution code:
#/usr/bin/python

def solve():
    n = int(input())
    a = sorted(map(int, input().split()), reverse=True)
    a2 = sum([[i, i] for i in a], []) # flatten
    a2[0] = 0
    return sum(a2[:n])

print(solve())

Submission status: Time Limit Exceeded

Solution code:
import sys

N = int(sys.stdin.readline())
A = [int(i) for i in sys.stdin.readline().split(' ')]

A.sort(reverse=True)
max_value = A.pop(0)
diff = [max_value]
ans = 0
for i in A:
    ans = ans + diff.pop(0)
    diff = diff + [i, i]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline

N = int(input())
A = [int(i) for i in input().split(' ')]

A.sort(reverse=True)
max_value = A.pop(0)
diff = [max_value]
ans = 0
for i in A:
    ans = ans + diff.pop(0)
    diff = diff + [i, i]

print(ans)

Submission status: Time Limit Exceeded

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

A.sort(reverse=True)
max_value = A.pop(0)
diff = [max_value]
ans = 0
for i in A:
    n = diff.pop(0)
    ans = ans + n
    diff = diff + [i, i]

print(ans)

Submission status: Time Limit Exceeded

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

max_value = A.pop(A.index(max(A)))
diff = [max_value]
ans = 0
for i in range(N - 1):
    ans = ans + max(diff)
    n = diff.index(max(diff))
    max_value = A.pop(A.index(max(A)))
    diff[n] = max_value
    diff.insert(n + 1, max_value)

print(ans)

Submission status: Time Limit Exceeded

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

A.sort(reverse=True)
max_value = A.pop(0)
diff = [max_value]
ans = 0
for i in A:
    ans = ans + max(diff)
    n = diff.index(max(diff))
    diff[n] = i
    diff.insert(n + 1, i)

print(ans)

Submission status: Time Limit Exceeded

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

A.sort(reverse=True)
ring = []
max_value = A.pop(0)
ring.append(max_value)
ring.append(max_value)
diff = [max_value]
ans = 0
flag = True
for i in A:
    ans = ans + max(diff)
    n = diff.index(max(diff))
    ring.insert(n + 1, i)
    diff[n] = i
    diff.insert(n + 1, i)

print(ans)

Submission status: Time Limit Exceeded

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

A.sort(reverse=True)
ring = []
max_value = A.pop(0)
ring.append(max_value)
ring.append(max_value)
ans = 0
flag = True
while len(A) != 0:
    i = A.pop(0)
    n = []
    if flag:
        for j in range(0, len(ring) - 1):
            check = min(ring[j:j + 2])
            n.append(check)
            flag = False
            if check == max(ring):
                break
    else:
        for j in range(len(ring), 1, -1):
            check = min(ring[j - 2:j])
            n.append(check)
            flag = True
            if check == max(ring):
                break
    ans = ans + max(n)
    ring.insert(n.index(max(n)) + 1, i)

print(ans)

Submission status: Time Limit Exceeded

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

A.sort(reverse=True)
ring = []
max_value = A.pop(0)
ring.append(max_value)
ring.append(max_value)
ans = 0

while len(A) != 0:
    i = A.pop(0)
    n = []
    for j in range(0, len(ring) - 1):
        check = min(ring[j:j + 2])
        n.append(check)
        if check == max(ring):
            break
    ans = ans + max(n)
    ring.insert(n.index(max(n)) + 1, i)

print(ans)

Submission status: Time Limit Exceeded

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

A.sort(reverse=True)
ring = []
max_value = A.pop(0)
ring.append(max_value)
ring.append(max_value)
ans = 0
for i in A:
    n = []
    for j in range(0, len(ring) - 1):
        check = min(ring[j:j + 2])
        n.append(check)
        if check == max(ring):
            break
    ans = ans + max(n)
    ring.insert(n.index(max(n)) + 1, i)

print(ans)

Submission status: Time Limit Exceeded

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

A.sort(reverse=True)
ring = []
max_value = A.pop(0)
ring.append(max_value)
ring.append(max_value)
ans = 0
for i in A:
    buf = [x for x in ring]
    n = []
    for j in range(0, len(ring) - 1):
        n.append(min(ring[j:j+2]))
    ans = ans + max(n)
    ring.insert(n.index(max(n)) + 1, i)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
# def main():
#     N=input()
#     N=int(N)
#     A=input().split(" ")
#     A=np.array([int(i) for i in A]).astype(np.uint64)
#     # A=np.random.randint(0,100000,200000)
#     l=[]
#     A=np.sort(A)
#     A=np.flip(A).astype(np.uint64)
#     sum=0
#     for i,num in enumerate(A):
#         if i%2==0:
#             l=l+[num]
#             if i!=0:
#                 sum+=min(l[-2],l[0])
#         else:
#             l=[num]+l
#             sum+=min(l[1],l[-1])
#     print(int(sum))

# def main2():
#     N=input()
#     N=int(N)
#     A=input().split(" ")
#     A=np.array([int(i) for i in A]).astype(np.uint64)
#     # A=np.random.randint(0,100000,200000)
#     A=np.sort(A)
#     A=np.flip(A).astype(np.uint64)
#     sum=0
#     for i,num in enumerate(A):
#         if i==0:
#             l=A[0]
#             r=A[0]
#             continue
#         sum+=min(l,r)
#         if l<r:
#             r=num
#         else:
#             l=num
#     print(int(sum))

def main3():
    N=input()
    N=int(N)
    A=input().split(" ")
    A=np.array([int(i) for i in A]).astype(np.uint64)
    l=[]
    A=np.sort(A)
    A=np.flip(A).astype(np.uint64)
    sum=0
    for i,num in enumerate(A):
        if i==0:
            l.append(num)
            continue
        l1=np.array(l,dtype=np.uint64)
        l2=np.roll(l1,1)
        l1=l1.reshape(-1,1)
        l2=l2.reshape(-1,1)
        l1=np.concatenate([l1,l2],1)
        l2=l1.min(1)
        arg=l2.argmax()
        l=l[:arg+1]+[num]+l[arg+1:]
        sum+=l2[arg]

    print(int(sum))

if __name__ == "__main__":
    main3()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
def main():
    N=input()
    N=int(N)
    A=input().split(" ")
    A=np.array([int(i) for i in A]).astype(np.uint64)
    # A=np.random.randint(0,100000,200000)
    l=[]
    A=np.sort(A)
    A=np.flip(A).astype(np.uint64)
    sum=0
    for i,num in enumerate(A):
        if i%2==0:
            l=l+[num]
            if i!=0:
                sum+=min(l[-2],l[0])
        else:
            l=[num]+l
            sum+=min(l[1],l[-1])
    print(int(sum))

def main2():
    N=input()
    N=int(N)
    A=input().split(" ")
    A=np.array([int(i) for i in A]).astype(np.uint64)
    # A=np.random.randint(0,100000,200000)
    A=np.sort(A)
    A=np.flip(A).astype(np.uint64)
    sum=0
    for i,num in enumerate(A):
        if i==0:
            l=A[0]
            r=A[0]
            continue
        sum+=min(l,r)
        if l<r:
            r=num
        else:
            l=num
    print(int(sum))

def main3():
    N=input()
    N=int(N)
    A=input().split(" ")
    A=np.array([int(i) for i in A]).astype(np.uint64)
    # A=np.random.randint(0,100000,200000)
    l=[]
    A=np.sort(A)
    A=np.flip(A).astype(np.uint64)
    sum=0
    for i,num in enumerate(A):
        if i==0:
            l.append(num)
            continue
        l1=np.array(l)
        l2=np.roll(l1,1)
        l1=l1.reshape(1,-1)
        l2=l2.reshape(1,-1)
        l1=np.concatenate([l1,l2],0)
        l1=np.transpose(l1)
        l2=l1.min(1)
        arg=l2.argmax()
        l=l[:arg+1]+[num]+l[arg+1:]
        sum+=l2[arg]

    print(int(sum))

if __name__ == "__main__":
    # main()
    # main2()
    main3()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))
sa = list(sorted(a, reverse=True))
min_a = min(a)
max_a = max(a)
x = max_a

order = []

while x >= min_a:
    try:
        idx = sa.index(max_a)
        order.append(max_a)
        sa.pop(idx)
    except ValueError:
        pass
    x -= 1

order = order + list(sorted(sa))
comfort = 0
x = min_a

while len(order):
    point = 0
    try:
        idx = order.index(x)
        ll = len(order)
        if ll == 1:
            point = 0
        elif ll == 2:
            if idx == 0:
                point = order[1]
            else:
                point = order[0]
        else:
            point = min(order[idx-1], order[idx+1])
        order.pop(idx)
    except ValueError:
        x += 1
        continue
    comfort += point

print(comfort)

Submission status: Time Limit Exceeded

Solution code:
MAX = 1e9+7

def main():
    N = int(input())
    nums = [int(i) for i in input().split(' ')]
    nums = sorted(nums, reverse=True)


    new_order = [MAX for i in range(N)]
    fri = [0 for i in range(N)]

    res = 0
    new_order[0] = fri[0] = nums[0]

    for len_ in range(1, N):
        num = nums[len_]
        max_ = max(fri[:len_])
        pos = fri.index(max_) + 1
        res += max_
        new_order.insert(pos, num)

        fri.insert(pos, min(new_order[pos], new_order[(pos+1)%len_]))
        fri[pos-1] = min(new_order[pos], new_order[(pos-1+len_)%len_])
    return res

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

Submission status: Time Limit Exceeded

Solution code:
MAX = 1e9+7

def main():
    N = int(input())
    nums = [int(i) for i in input().split(' ')]
    nums = sorted(nums, reverse=True)
    new_order = [MAX for i in range(N)]
    fri = [0 for i in range(N)]
    # max_ = 0
    res = 0
    new_order[0] = fri[0] = nums[0]

    # print(new_order)
    # print(fri)
    # print('*'*39)

    for len_ in range(1, N):
        num = nums[len_]
        max_ = max(fri)
        pos = fri.index(max_) + 1
        res += max_
        new_order.insert(pos, num)

        fri.insert(pos, min(new_order[pos], new_order[(pos+1)%len_]))
        fri[pos-1] = min(new_order[pos], new_order[(pos-1+len_)%len_])
        # max_ = max([fri[pos], fri[pos-1], max_])

        # print(new_order)
        # print(fri)
        # print('*'*39)
    return res

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

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A = list(map(int,input().split()))
A.sort(reverse=True)
circle=[]

conf_sum=0
for a in A:
    max_conf=0
    index=0
    if len(circle) != 0:
        pairs=[min(circle[i],circle[i+1]) for i in range(len(circle)-1)]
        pairs.append(min(circle[0],circle[-1]))
        max_conf=max(pairs)
        index=pairs.index(max_conf)+1
    conf_sum+=max_conf
    circle.insert(index,a)
# =============================================================================
#     for i in range(len(circle)):
#         if i==len(circle)-1:
#             conf=min(circle[i],circle[0])
#         else:
#             conf=min(circle[i],circle[i+1])
#         if conf>max_conf:
#             max_conf=conf
#             index=i+1
# =============================================================================
    
    
            
print(conf_sum)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A = list(map(int,input().split()))
A.sort(reverse=True)
circle=[]

conf_sum=0
for a in A:
    max_conf=0
    index=0
    for i in range(len(circle)):
        if i==len(circle)-1:
            conf=min(circle[i],circle[0])
        else:
            conf=min(circle[i],circle[i+1])
        if conf>max_conf:
            max_conf=conf
            index=i+1
    conf_sum+=max_conf
    circle.insert(index,a)
    
            
print(conf_sum)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

a = list(map(int, input().split()))
a = sorted(a, reverse=True)
comfort = a[0:2]
sum = max(a[0], a[1])
for j in a[2:]:
    key = 0
    for i in range(len(comfort) - 1):
        comfort_value = min(comfort[1], comfort[-1])
        comfort_value_kari = min(comfort[i], comfort[i + 1])
        if comfort_value < comfort_value_kari:
            comfort_value = comfort_value_kari
            key = i
    comfort.insert(key, j)
    sum += comfort_value
print(sum)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

a.sort()
arrived = [a.pop()]
comfort = [arrived[0]]
score = 0

for i in range(n - 1):
    x = a.pop()
    max_index = np.argmax(comfort)
    score += comfort[max_index]

    arrived.insert(max_index + 1, x)
    comfort[max_index] = min(arrived[max_index], x)
    comfort.insert(max_index + 1, min(x, arrived[max_index + 1]))

print(score)

Submission status: Time Limit Exceeded

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

a.sort()

arrived = []
score = 0
for i in range(n):
    x = a.pop()
    _max = [0, 0]
    for j in range(len(arrived)):
        if _max[0] < (_min := min(arrived[j - 1], arrived[j])):
            _max = [_min, j + 1]
    arrived.insert(_max[1], x)
    score += _max[0]
print(score)

Submission status: Time Limit Exceeded

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

seat = []
seat.append(0)
seat.append(1)

A = []
for i in range(N):
    A.append(max(B))
    B.remove(max(B))

comfortable = [0, A[0]]

for i in range(2,N):
    comfortable_chance = []
    for seat_occupied in range(i-1):
        comfortable_chance.append(min(A[seat[seat_occupied]],A[seat[seat_occupied+1]]))
    comfortable_chance.append(min(A[seat[-1]],A[seat[0]]))
    comfortable_seat = comfortable_chance.index(max(comfortable_chance))+1
    comfortable.append(max(comfortable_chance))
    seat.insert(comfortable_seat, i)

print(sum(comfortable))

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=input().split()
a.sort(reverse=True)
a_min=[a[0]]
a_s=[a[0]]
comf=0
for i in range(n-1):
  a_min=[min(a_s[j-1],a_s[j]) for j in range(len(a_s))]
  a_minn=[int(i) for i in a_min]
  m=max(a_minn)
  ind=a_min.index(str(m))
  a_s.insert(ind,a[i+1])
  comf+=int(m)
print(comf)

Submission status: Time Limit Exceeded

Solution code:
import copy
n=int(input())
a=input().split()
a_order=list(sorted(a,reverse=True))
a_min=[a_order[0]]
a_s=copy.copy(a_min)
comf=0
for i in range(n-1):
  a_min=[min(a_s[j-1],a_s[j]) for j in range(len(a_s))]
  a_minn=[int(i) for i in a_min]
  m=max(a_minn)
  ind=a_min.index(str(m))
  a_s.insert(ind,a_order[i+1])
  comf+=int(m)
print(comf)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
a = deque(sorted(list(map(int, input().split())), reverse=True))
count = 0
ans = 0
arrive = [a[0], a[1]]


def maxi():
    maxi_num = 0
    bef_maxi = 0
    maxi_posit = 0
    for i in range(len(arrive)):
        bef_num = maxi_num
        if i == len(arrive) - 1:
            maxi_num = max(maxi_num, min(arrive[i], arrive[0]))
        else:
            maxi_num = max(maxi_num, min(arrive[i], arrive[i + 1]))
        if maxi_num != bef_num:
            maxi_posit = i + 1
    return maxi_posit, maxi_num


while n > count:
    if count == 0:
        a.popleft()
    elif count == 1:
        ans += arrive[0]
        a.popleft()
    else:
        res = maxi()
        ans += res[1]
        arrive.insert(res[0], a.popleft())
    count += 1
print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
f = [int(s) for s in input().split()]
f = sorted(f, reverse=True)
total = 0
s = []
for i in range(n):
  if i == 0:
    s.append(f[i])
  elif i == 1:
    total += s[0]
    s.append(f[i])
  else:
    tmp = []
    for j in range(len(s)):
      k = j - 1
      if s[j] <= s[k]:
        tmp.append(s[j])
      else:
        tmp.append(s[k])
    total += max(tmp)
    s.append(f[i])
print(total)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
f = [int(s) for s in input().split()]
f = sorted(f, reverse=True)
total = 0
s = []
for i in range(n):
  if i == 0:
    s.append(f[i])
  elif i == 1:
    total += s[0]
    s.append(f[i])
  else:
    max = 0
    for j in range(len(s)):
      k = j - 1
      if s[j] <= s[k] and s[j] >= max:
        max = s[j]
      elif s[j] > s[k] and s[k] >= max:
        max = s[k]
    total += max
    s.append(f[i])
print(total)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
friendly = [int(i) for i in input().split()]
friendly.sort(reverse=True)
place = []
place.append(friendly[0])
place=place*2
ans=0
for i in friendly[1:]:
    comfortable=[min(place[i], place[i+1]) for i in range(len(place)-1)]
    ans += max(comfortable)
    place.insert(comfortable.index(max(comfortable))+1, i)
print(ans)

Submission status: Time Limit Exceeded

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

N = int(input())
A = list(map(int, input().split()))
ans = 0
for L in itertools.permutations(A):
    temp = 0
    for i in range(1, N):
        temp += min(L[0], L[i-1])
    ans = max(ans, temp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

players = list(map(int, input().split()))
players.sort(reverse=True)

total = 0
if len(players) > 1:
    total = 0
    place = []
    for i, player in enumerate(players):
        if i == 0:
            place.append(player)
        elif i == 1:
            total += players[0]
            place.append(player)
        elif i == 2:
            total += players[1]
            place.append(player)
        else:
            shifted_place = [place[-1]]
            shifted_place.extend(place[:-1])
            comfort_list = list(map(min, place, shifted_place))
            max_comfort = max(comfort_list)
            total += max_comfort
            max_comfort_index = comfort_list.index(max_comfort)
            place.insert(max_comfort_index, player)

print(total)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

players = list(map(int, input().split()))
players.sort(reverse=True)

total = 0
if len(players) > 1:
    total = 0
    place = []
    for i, player in enumerate(players):
        if i == 0:
            place.append(player)
        elif i == 1:
            total += players[0]
            place.append(player)
        elif i == 2:
            total += players[1]
            place.append(player)
        else:
            max_comfort = 0
            max_comfort_index = 0
            for j, p in enumerate(place):
                comfort = min(p, place[j - 1])
                if comfort > max_comfort:
                    max_comfort = comfort
                    max_comfort_index = j
            total += max_comfort
            place.insert(max_comfort_index, player)

print(total)

Submission status: Time Limit Exceeded

Solution code:
a = int(input())
b = list(map(int,input().split()))
ans = 0
c = 0
list.sort(b, reverse=True)
ans += b.pop(0)
b.extend(b)
list.sort(b, reverse=True)

for i in range(2,a):
    ans += b.pop(0)
print(str(ans))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
a = list(map(int, input().split()))

a.sort(reverse=True)
a = deque(a)
circle = []
circle.append(a.popleft())

ans = 0
while a:
    nex = a.popleft()
    mx = 0
    for i in range(len(circle)):
        if mx <= min(circle[i-1], circle[i]):
            mx = min(circle[i-1], circle[i])
            mx_idx = i
    ans += mx
    circle.insert(mx_idx, nex)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
input()
l = sorted(map(int, input().split(' ')))

answer = 0
spots = [l.pop()]

while l:
	n = l.pop()
	answer += spots[0]
	spots = spots[1:] + [n] * 2

print(answer)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
alist = list(map(int, input().split()))
alist.sort(reverse=True)
sumscore=0
posit = list()
posit.append(alist[0])
for n in range(1,N):
  sumscore = sumscore + posit[0]
  posit = posit[1:]
  posit.append(alist[n])
  posit.append(alist[n])

print(sumscore)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
A.sort()
ans = 0
confo = [A[N-1]]
for i in range(N-1):
	ans += confo[0]
	confo.append(A[N-i-2])
	confo.append(A[N-i-2])
	del confo[0]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
A=list(map(int,input().split()))
A.sort()
A.reverse()
ans=0
conf=[A[0]]
A.pop(0)


for elem in A:
    ans+=conf.pop(0)
    
    for _ in range(2):
        conf.append(elem)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())

arr=list(map(int,input().split()))
arr.sort()

dp=[arr.pop(-1)]
ans=0



for i in range(N-1):
    a=arr.pop()
    b=0
    kari=0

    for j in range(len(dp)):
        c=j+1
        if c>=len(dp):
            c=len(dp)-c
        if b<min(dp[j],dp[c]):
           b=min(dp[j],dp[c])
           kari=j+1
    dp.insert(kari,a)
    ans+=b
    
       
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def nth_element(array, will):
    will -= 1
    n = len(array)
    left = 0
    right = n-1
    while right > left:
        i = left-1
        j = right
        v = array[right]
        while True:
            i += 1
            j -= 1
            while array[i]<v:i+=1
            while array[j]>v:j-=1
            if i>=j:break
            array[i],array[j] = array[j],array[i]
        array[i],array[right] = array[right],array[i]
        if i == will:break
        if i > will:
            right = i-1
        else:
            left = i+1
    return array

# from random import randrange
# for i in range(100):

n = int(input())
A = list(map(int,input().split()))
# n = randrange(2,10)
# A = [0]*n
# for j in range(n):
#     A[j] = randrange(1,1000)
k = 1 + (n-1)//2

nth_element(A,n-k+1)
# B = sorted(A)
ans = 0
M = 0
# m = B[-1]
for i in range(-1,n-1):
    ans += A[n - (i+1)//2 - 1]
    M = max(M, A[n- (i+1)//2 - 1])
    # ans -= B[n-(i+1)//2 - 1]
ans -= M
# ans += m
# if ans != 0:
#     print(n,A)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input());
A = [int(x) for x in input().split()];
A.sort(reverse=True);
#print(A);
c =[];
c.append(A[0]);
confort = 0;
c.append(A[1]);
confort = A[0];
for i in range(2,N) :
    con = 0;
    k = 0;
    for j in range(0,len(c)) :
        if min(c[j-1],c[j]) > con :
            con = min(c[j-1],c[j]);
            k = j;
    c.insert(j,A[i]);
    confort += con;
    #print(c,confort)
    
print(confort);
#print(sum(A)-min(A));

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import collections


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


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


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


def main():
    N = II()
    As = LI()
    As.sort()
    As.reverse()
    ans = []
    ans.append(As.pop(0))
    N -= 1

    for i in range(len(As)):
        tmp = As.pop(0)
        ans.extend([tmp, tmp])

    print(sum(ans[:N]))


# oj t -c "pypy3 main.py"
# acc s main.py -- --guess-python-interpreter pypy
main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

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

dic = {}
lis = []
for i in a:
    if i in dic:
        dic[i] = dic[i] + 1
    else:
        dic[i] = 1
        lis.append(i)

lis.sort()
lis.reverse()

ans = 0
n -= 1
for i in lis:
    if max(lis) == i:
        k = 2 * dic[i] - 1
    else:
        k = 2 * dic[i]
    if n - k >= 0:
        ans += i * k
    else:
        ans += i * n
        break
    n -= k

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=list(map(int,input().strip().split()))
a.sort(reverse=True)
na=[]
cost=0
na.append(a[0])
na.append(a[1])
cost+=a[0]
for i in range(2,n):
    s=[]
    for j in range(len(na)-1):
        s.append([min(na[j],na[j+1]),j])
    s=sorted(s)
    s=s[::-1]
    #print(s,na[:s[0][1]+1],a[i],na[s[0][1]+1:])
    na=na[:s[0][1]+1]+[a[i]]+na[s[0][1]+1:]
    cost+=s[0][0]
    #print(na)
print(cost)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
arr = list(map(int,input().split()))
arr.sort()
arr = arr[-1::-1]
s = 0
q = [[arr[0],arr[0]]]
for i in range(1,n):
    u = q[0]
    q.pop(0)
    s+=min(u[0],u[1])
    q.append([u[0],arr[i]])
    q.append([arr[i],u[1]])
print(s)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
lsA = list(map(int,input().split()))
lsA += lsA
lsA.sort(reverse=True)

lsA.pop(0)
ans = 0
for i in range(N-1):
    ans += lsA.pop(0)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import namedtuple

import numpy as np

sys.setrecursionlimit(10**6)

length = int(sys.stdin.readline())

values = np.array([int(i) for i in sys.stdin.readline().split()], dtype=np.int32)
values = np.sort(values)[::-1]

next_ptr = np.zeros(shape=values.shape, dtype=np.int32)-1
next_ptr[0] = 0

total_score = 0
for index in range(1, len(values)):
  best_index = 0
  best_score = 0
  i = np.where(next_ptr>=0)[0]
  next_i = next_ptr[i]
  values_i = values[i]
  next_values_i = values[next_i]
  scores = np.min([values_i, next_values_i], axis=0)
  best_index = np.argmax(scores)
  
  total_score += scores[best_index]
  
  next_ptr[index] = next_ptr[best_index]
  next_ptr[best_index] = index
  
print(total_score)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A = list(map(int, input().strip().split()))
import statistics

def quickSort(arr):

    # 配列のメジアンより小さい要素を集めた配列
    left = []

    # 配列のメジアンより大きい要素を集めた配列
    right = []

    # 再帰の停止条件
    # 再帰的に配列を分割した後の、要素数が1以下になったら停止する
    if len(arr) <= 1:
        return arr

    # 配列の中央値(メジアン)を取得する
    median = int(statistics.median(arr))

    # 配列内に含まれる中央値の個数を数えるための変数
    medianFlg = 0

    for element in arr:
        # 配列の要素(element)が中央値より小さいので、
        # 配列leftに値を格納する
        if element < median:
            right.append(element)
        # 配列の要素(element)が中央値より大きいので、
        # 配列rightに値を格納する
        elif element > median:
            left.append(element)
        else:
        # elementが配列の中央値の場合は、
        # 返り値に加える中央値の個数分だけ、フラグに+1し続ける
            medianFlg += 1

    # 配列left、配列right毎に再帰を行い
    # 配列を小さな配列に区切る
    left = quickSort(left)
    right = quickSort(right)

    # 配列left、中央値の[median]、配列rightを結合したものを返す
    return left + [median] * medianFlg + right

A=quickSort(A)
count=2
ans=A[0]
A.pop(0)
while count<N:
    add_num=A.pop(0)
    ans+=add_num*2
    count+=2
    if count>N:
        ans=ans-add_num

print("{}".format(ans))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
#A=[1,1,1,1,1,1,1]
#N=7
A.sort(reverse=True)
dis=[A[0]]
num=0
for i in range(1,len(A)):
    ind=0
    num+=dis.pop(ind)
    #L.insert(ind+1,A[i])
   
    dis.append(A[i])
    dis.append(A[i])
print(num)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import namedtuple

class Inst:
  def __init__(self, value, next=None):
    self.value = value
    if next is None:
      self.next = self
    else:
      self.next = next
    
#Inst = namedtuple('Inst', ('value', 'next'))

length = int(sys.stdin.readline())

array = sorted([int(i) for i in sys.stdin.readline().split()], reverse=True)

values = array
next_ptr = [-1 for _ in values]
next_ptr[0] = 0

total_score = 0
for index in range(1, len(array)):
  #print('----------')
  #print("ADDING {}".format(values[index]))
  best_index = 0
  best_score = 0
  for i, next_i in enumerate(next_ptr):
    if next_i < 0:
      break
    
    score = min(values[i], values[next_i])
    #print(i, next_i, values[i], values[next_i], score)
    
    if score > best_score:
      best_index, best_score = i, score
  
  #print("CHOOSE: {}({})-{}({})-{}({}): {}".format(
  #  values[best_index], 
  #  best_index,
  #  values[index],
  #  index,
  #  values[next_ptr[best_index]], 
  #  next_ptr[best_index],
  #  best_score))
  total_score += best_score
  
  next_ptr[index] = next_ptr[best_index]
  next_ptr[best_index] = i
  
  #print('----- TEST -----')
  #index = 0
  #while True:
  #  print(values[index])
  #  index = next_ptr[index]
  #  if index == 0:
  #    break

#print("ANSWER")
print(total_score)