Problem:


Score : 500 points

Problem Statement

There are N children standing in a line from left to right. The activeness of the i-th child from the left is A_i.

You can rearrange these children just one time in any order you like.

When a child who originally occupies the x-th position from the left in the line moves to the y-th position from the left, that child earns A_x \times |x-y| happiness points.

Find the maximum total happiness points the children can earn.

Constraints

2 \leq N \leq 2000

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum total happiness points the children can earn.

Sample Input 1

4
1 3 4 2

Sample Output 1

20

If we move the 1-st child from the left to the 3-rd position from the left, the 2-nd child to the 4-th position, the 3-rd child to the 1-st position, and the 4-th child to the 2-nd position, the children earns 1 \times |1-3|+3 \times |2-4|+4 \times |3-1|+2 \times |4-2|=20 happiness points in total.

Sample Input 2

6
5 5 6 1 1 1

Sample Output 2

58

Sample Input 3

6
8 6 9 1 2 1

Sample Output 3

85



Sample input:
4
1 3 4 2


Sample output:
20

Submission status: Runtime Error

Solution code:
n = int(input())
a = list(map(int, input().split()))
s = [0 for _ in range(n)]

score = 0
for i in range(n):
    l = s.index(0)
    r = s[::-1].index(0)
    #right
    score_r, score_l = score, score
    sr, sl = s.copy(), s.copy()
    if r >= i:
        sr[r] = a[i]
        score_r += a[i] * (r - i)
        while r < n-1 and sr[r] > sr[r+1]:
            score_r += sr[r] - sr[r+1]
            sr[r], sr[r+1] = sr[r+1], sr[r]
            r += 1

    if l <= i:
        sl[l] = a[i]
        score_l += a[i] * (i - l)
        while l > 0 and sl[l-1] < sl[l]:
            score_l += sl[l] - sl[l-1]
            sl[l-1], sl[l] = sl[l], sl[l-1]
            l += 1

    if score_r >= score_l:
        score = score_r
        s = sr

    else:
        score = score_l
        s = sl


print(score)
#print(s)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
n=int(input())
A=[int(i) for i in input().split()]
#A=[1,10,2,4,3,9,5,7]
#A=[8,6,9,1,2,1]
peak=[]

keep = A[0]

def f(A):
    idx=defaultdict(list)
    for i,a in enumerate(A):
        idx[a].append(i)
    return idx
def calc(ida,idb,aa):
    dist = 0
    for i in aa:
        l1 = ida[i]
        l2 = idb[i]
        l1.sort()
        l2.sort()
        m1 = sum([abs(i-j) for i,j in zip(l1,l2[::-1])])
        m2 = sum([abs(i-j) for i,j in zip(l1[::-1],l2)])
        #print(i,max(m1,m2)*i)
        dist+=max(m1,m2)*i
    return dist

for i in range(1,len(A)):
    if keep>A[i]:
        l = A[:i-1]
        r = A[i-1:]
        l.sort()
        r.sort(reverse=True)
        #print(r,l)
        r.extend(l)
        peak.append(r)
        l = A[:i]
        r = A[i:]
        l.sort()
        r.sort(reverse=True)
        #print(r,l)
        r.extend(l)
        peak.append(r)
    keep = A[i]

if len(peak) == 0:
    if len(A)%2==0:
        yy = len(A)//2
        B=A[yy:][::-1]
        B.extend(A[:yy])
        ida =f(A)
        idb =f(B)
        #print(calc(ida,idb,aa))
        cal = calc(ida,idb,aa)
        print(cal)
    else:
        yy = len(A)//2 + 1
        B=A[yy:][::-1]
        B.extend(A[:yy])
        ida =f(A)
        idb =f(B)
        #print(calc(ida,idb,aa))
        cal = calc(ida,idb,aa)
        print(cal)
else:
    ans = 0
    for B in peak:
        aa = set(A)
        ida =f(A)
        idb =f(B)
        #print(calc(ida,idb,aa))
        cal = calc(ida,idb,aa)
        ans = max(ans,cal)
    print(ans)

Submission status: Runtime Error

Solution code:
import itertools

N=int(input())
actlist=list(map(int,input().split()))
alllist=list(itertools.permutations(range(1,N+1)))

count=1

hapsum=0
for i in range(N-1):
    for j in (i+1,N):
        maxnum=0
        for m,n in zip(alllist[i],alllist[j]):
            hapsum+=actlist[i]*abs(m-n)
        if maxnum<hapsum:
            maxnum=hapsum
        

print(maxnum)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
n=int(input())
A=[int(i) for i in input().split()]
#A=[1,10,2,4,3,9,5,7]
#A=[8,6,9,1,2,1]
peak=[]

keep = A[0]

def f(A):
    idx=defaultdict(list)
    for i,a in enumerate(A):
        idx[a].append(i)
    return idx
def calc(ida,idb,aa):
    dist = 0
    for i in aa:
        l1 = ida[i]
        l2 = idb[i]
        l1.sort()
        l2.sort()
        m1 = sum([abs(i-j) for i,j in zip(l1,l2[::-1])])
        m2 = sum([abs(i-j) for i,j in zip(l1[::-1],l2)])
        #print(i,max(m1,m2)*i)
        dist+=max(m1,m2)*i
    return dist

for i in range(1,len(A)):
    if keep>A[i]:
        l = A[:i-1]
        r = A[i-1:]
        l.sort()
        r.sort(reverse=True)
        #print(r,l)
        r.extend(l)
        peak.append(r)
        l = A[:i]
        r = A[i:]
        l.sort()
        r.sort(reverse=True)
        #print(r,l)
        r.extend(l)
        peak.append(r)
    keep = A[i]

if len(peak) == 0:
    if len(A)%2==0:
        yy = len(A)//2
        B=A[yy:][::-1]
        B.extend(A[:yy]
        ida =f(A)
        idb =f(B)
        #print(calc(ida,idb,aa))
        cal = calc(ida,idb,aa)
        print(cal)
    else:
        yy = len(A)//2 + 1
        B=A[yy:][::-1]
        B.extend(A[:yy])
        ida =f(A)
        idb =f(B)
        #print(calc(ida,idb,aa))
        cal = calc(ida,idb,aa)
        print(cal)
else:
    ans = 0
    for B in peak:
        aa = set(A)
        ida =f(A)
        idb =f(B)
        #print(calc(ida,idb,aa))
        cal = calc(ida,idb,aa)
        ans = max(ans,cal)
    print(ans)

Submission status: Runtime Error

Solution code:

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

b = [0]*n
after = [-1]*n

print(b)
for num,i in enumerate(a):
    b[i-1]=num

for j in range(0,n,-1):
    top = 0
    tail = n
    while True:
        if j-top > tail - j:
            if after[top] == -1:
                after[top] ==j-top
                break
            else:
                top+= 1
        else:
            if after[tail] == -1:
                after[tail] ==tail-j
                break
            else:
                tail-= 1

print(sum(after))

Submission status: Runtime Error

Solution code:
N = int(input())
A = [(int(a), i) for i, a in enumerate(input().split())]
A = sorted(A, reverse=True)

memo = {}

def solve(i, l, r):
    if i==N: return 0
    a, loc = A[i]
    score_l = a*abs(l-loc) + solve(i+1, l+1, r)
    score_r = a*abs(r-loc) + solve(i+1, l, r-1)
    retval = max(score_l, score_r)
    key = (i,l,r)
    if key not in memo: memo[key]=retval
    return retval
    
print(solve(0, 0, N-1))

Submission status: Runtime Error

Solution code:
from collections import defaultdict
n=int(input())
A=[int(i) for i in input().split()]
#A=[1,10,2,4,3,9,5,7]
#A=[8,6,9,1,2,1]
peak=[]

keep = A[0]

def f(A):
    idx=defaultdict(list)
    for i,a in enumerate(A):
        idx[a].append(i)
    return idx
def calc(ida,idb,aa):
    dist = 0
    for i in aa:
        l1 = ida[i]
        l2 = idb[i]
        l1.sort()
        l2.sort()
        m1 = sum([abs(i-j) for i,j in zip(l1,l2[::-1])])
        m2 = sum([abs(i-j) for i,j in zip(l1[::-1],l2)])
        #print(i,max(m1,m2)*i)
        dist+=max(m1,m2)*i
    return dist

for i in range(1,len(A)):
    if keep>A[i]:
        l = A[:i-1]
        r = A[i-1:]
        l.sort()
        r.sort(reverse=True)
        #print(r,l)
        r.extend(l)
        peak.append(r)
        l = A[:i]
        r = A[i:]
        l.sort()
        r.sort(reverse=True)
        #print(r,l)
        r.extend(l)
        peak.append(r)
    keep = A[i]

if len(peak) == 0:
    if len(A)%2==0:
        yy = len(A)//2
        B=A[yy:]
        B.extend(A[:yy])
        ida =f(A)
        idb =f(B)
        #print(calc(ida,idb,aa))
        cal = calc(ida,idb,aa)
        print(cal)
    else:
        yy = len(A)//2 + 1
        B=A[yy:]
        B.extend(A[:yy])
        ida =f(A)
        idb =f(B)
        #print(calc(ida,idb,aa))
        cal = calc(ida,idb,aa)
        print(cal)
else:
    ans = 0
    for B in peak:
        aa = set(A)
        ida =f(A)
        idb =f(B)
        #print(calc(ida,idb,aa))
        cal = calc(ida,idb,aa)
        ans = max(ans,cal)
    print(ans)

Submission status: Runtime Error

Solution code:
n=int(input())
a=list(map(int,input().split()))
y=n-1
x=0
s=0
for i in range(n):
    b=max(a)
    m=a.index(b)
    if abs(m-x)>abs(y-m):
        s+=b*abs(m-x)
        x+=1
    else:
        s+=b*abs(y-m)
        y-=1


    a.remove(a)
print(s)

Submission status: Runtime Error

Solution code:
N=int(input())
A=[]
for i,a in enumerate(map(int,input().split())):
  A.append([a,i])
A=sorted(A,key=lambda x:x[0], reverse=True)
r,l=0,N-1
ans=0
i=0
while r<=l:
  _=[A[i]]
  i+=1
  while i<N and A[i][0]==_[0][0]:
    _.append(A[i])
    i+=1
  _=sorted(_,key=lambda x:x[1],reverse=True)
  k=-1
  for _k in range(len(_)):
    if k==-1:
      k=0
    else:
      k=len(_)-1-k
      if k<len(_)//2:
        k+=1    
  a,j=_[k]
    if (l+r)/2<j:
      ans+=a*(j-r)
      r+=1
    else:
      ans+=a*(l-j)
      l-=1
print(ans)

Submission status: Runtime Error

Solution code:
n=int(input())
import numpy as np
a=list(map(int,input().split()))
l=[]
for i in range(n):
    l.append((a[i],i))
l.sort(reverse=True) 
left=0
right=n-1
ans=0
for j in range(n):
    i=l[j]
    i_next=l[j]+
    if abs(right-i[1])==abs(i[1]-left):
        if n-1-right>=left:
            ans+=i[0]*abs(right-i[1])
            right-=1
            
        else:
            ans+=i[0]*abs(i[1]-left)
            left+=1
    elif abs(right-i[1])<abs(i[1]-left):
        ans+=i[0]*abs(i[1]-left)
        left+=1
    else:
        ans+=i[0]*abs(right-i[1])
        right-=1 

print(ans)

Submission status: Runtime Error

Solution code:
n=int(input())
a=list(map(int,input().split()))
y=n-1
x=0
s=0
for i in range(n):
    b=max(a)
    m=a.index(a)
    if abs(m-x)>abs(y-m):
        s+=b*abs(m-x)
        x+=1
    else:
        s+=b*abs(y-m)
        y-=1


    a.remove(a)
print(s)

Submission status: Runtime Error

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(range(N))
Aleft=0
Aright=0
Aleftlist=[]
Arightlist=[]
Amax=0
Amaxmax=0
Apoint=0
Bpoint=0
check=0
for i in range(N):
  Amax=0
  Apoint=0
  Bpoint=0
  check=0
  for j in range((N-i)//2):
    if Amax<A[B[j]*(N-i-j):
      Amax=A[B[j]]*(N-i-j)
      Apoint=B[j]
      Bpoint=j
  for j in range((N-i)//2,N-i):
    if Amax<A[B[j]]*j:
      Amax=A[B[j]]*j
      Apoint=B[j]
      Bpoint=0
      check=1
  Amaxmax+=Amax
  A[Apoint]=0
  del B[Bpoint]
  if check==0:
     Aleft+=1
  else:
     Aright+=1
print(Amaxmax)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-


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

    a_ind = range(n)
    a_ind_s = sorted(a_ind, key=lambda x: a_list[x], reverse=True)

    def max_ans(a_i, s_min, s_max):
        if len(a_ind_s) <= a_i:
            return 0
        i = a_ind_s[a_i]
        a = a_list[i]

        return max(a * (s_max - i) + max_ans(a_i + 1, s_min, s_max - 1),
                   a * (i - s_min) + max_ans(a_i + 1, s_min + 1, s_max))

    r = max_ans(0, 0, n - 1)
    print(r)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n=int(input())
a=list(map(int,input()))
y=n-1
x=0
s=0
for i in range(n):
    b=max(a)
    m=a.index(a)
    if abs(m-x)>abs(y-m):
        s+=b*abs(m-x)
        x+=1
    else:
        s+=b*abs(y-m)
        y-=1


    a.remove(a)
print(s)

Submission status: Runtime Error

Solution code:
import numpy as np
import math

N = int(input())
A = [int(x) for x in input().split()]
B = list(range(1,N+1))
C = [0]*N
sum = 0

for i in range(N):
    d=0
    l=0
    m_k=0
    j = np.argmax(A)
    
    for k in B:
        l = abs(k-(j+1))
        if l > d:
            d = l
            m_k = k
    sum = sum + d*A[j]
    C[m_k-1]=A[j]
    B.remove(m_k)
    A[j]=0
print(sum)

Submission status: Runtime Error

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

import math
from itertools import permutations

lis = [0]*N
for i in range(N):
    lis[i] = i

num = math.factorial(N)

scores = [0] * num
for i, v in enumerate(permutations(lis, N)):
    score = 0
    for j in range(N):
        score += abs(v.index(j)-j) * A[j]
    scores[i] = score

print(max(scores))

Submission status: Runtime Error

Solution code:
N = int(input())
A = list(map(int,input().split()))
count = 0
ans = 0
fa = [n for n in range(N)]
while count < N:
    i = A.index(max(A))
    d = 0
    ra = 0
    for a in fa:
        dd = abs(i -a)
        if dd > d:
            d = dd
            ra = a
    fa.remove(ra)
    ans += d * max(A)
    A[i] = 0
    count += 1
print(ans)

Submission status: Runtime Error

Solution code:
def dfs(sude,sho,dai,ki):
    #print("新しい",sude,sho,dai,ki)
    global a,n
    #print(a,n)
    if(n==ki):
        return 0
    koho=[]
    saidai=-1
    for i in range(n):
        if(sude[i]):
            continue
        mae=abs(sho-i)
        usiro=abs(dai-i)
        #print(sho,dai,i,mae,usiro)
        if(mae<usiro):
            if(a[i]*usiro>saidai):
                koho=[[i,1]]
                saidai=a[i]*usiro
            elif(a[i]*usiro==saidai):
                koho.append([i,1])
        elif(usiro<mae):
            if(a[i]*mae>saidai):
                koho=[[i,-1]]
                saidai=a[i]*mae
            elif(a[i]*mae==saidai):
                koho.append([i,-1])
        else:
            if(a[i]*mae>saidai):
                saidai=a[i]*mae
                koho=[[i,-1],[i,1]]
            elif(a[i]*mae==saidai):
                koho.append([i,-1])
                koho.append([i,1])
    result_max=-1
    for k in koho:
        sude_co=sude[:]
        sude_co[k[0]]=True
        kekka=-1
        if(k[1]==-1):
            kekka=dfs(sude_co,sho+1,dai,ki+1)+a[k[0]]*abs(sho-k[0])
        else:
            kekka=dfs(sude_co,sho,dai-1,ki+1)+a[k[0]]*abs(dai-k[0])
        if(result_max<kekka):
            result_max=kekka
    #print(koho)
    return result_max


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

ans=0
sude=[False]*n

print(dfs(sude,0,n-1,0))

#sho=0
#dai=n-1
#for i in range(n):
#    saiyo_val=-1
#    saiyo_num=-1
#    tiisaiho=False
#    for j in range(n):
#        if(sude[j]):
#            continue
#        saidai_kyori=max(abs(sho-j),abs(dai-j))
#        if(a[j]*saidai_kyori>saiyo_val):
#            saiyo_val=a[j]*saidai_kyori

Submission status: Runtime Error

Solution code:
n = int(input())
a = list(map(int, input().split()))
s = [0 for _ in range(n)]

score = 0
for i in range(n):
    l = s.index(0)
    r = s[::-1].index(0)
    #right
    score_r, score_l = score, score
    if r >= i:
        sr = s.copy()
        sr[r] = a[i]
        score_r += a[i] * (r - i)
        while r < n-1 and sr[r] > sr[r+1]:
            score_r += sr[r] - sr[r+1]
            sr[r], sr[r+1] = sr[r+1], sr[r]
            r += 1

    if l <= i:
        sl = s.copy()
        sl[l] = a[i]
        score_l += a[i] * (i - l)
        while l > 0 and sl[l-1] < sl[l]:
            score_l += sl[l] - sl[l-1]
            sl[l-1], sl[l] = sl[l], sl[l-1]
            l += 1

    if score_r >= score_l:
        score = score_r
        s = sr

    else:
        score = score_l
        s = sl


print(score)

Submission status: Runtime Error

Solution code:
AAwIdx = [[0]*2 for _ in range(N)]
for i in range(N):
    AAwIdx[i][0] = i
    AAwIdx[i][1] = AA[i]
AA_sorted = sorted(AAwIdx, key=lambda x: x[1], reverse=True)
#print(AA_sorted)
Idx_i = 0
Idx_f = N-1
AnsIdx = [0]*N
#print(Idx_f)
answer = 0
for i in range(N):
    if Idx_f - AA_sorted[i][0] > AA_sorted[i][0] - Idx_i:
        AnsIdx[AA_sorted[i][0]] = Idx_f
        #answer += abs(AA_sorted[i][0]-Idx_f)*AA_sorted[i][1]
        Idx_f -= 1
    else:
        AnsIdx[AA_sorted[i][0]] = Idx_i
        #answer += abs(AA_sorted[i][0]-Idx_i)*AA_sorted[i][1]
        Idx_i += 1
    #print(AA_sorted[i][0],Idx_i,Idx_f)
for i in range(N):
    answer += abs(AAwIdx[i][0] - AnsIdx[i])*AAwIdx[i][1]
answerb = 0
Idx_i = 0
Idx_f = N-1
AnsIdx = [0]*N
if Idx_f - AA_sorted[0][0] > AA_sorted[0][0] - Idx_i:
    AnsIdx[AA_sorted[i][0]] = Idx_i
    #answer += abs(AA_sorted[i][0]-Idx_i)*AA_sorted[i][1]
    Idx_i += 1
else:
    AnsIdx[AA_sorted[i][0]] = Idx_f
    #answer += abs(AA_sorted[i][0]-Idx_f)*AA_sorted[i][1]
    Idx_f -= 1
for i in range(1,N):
    if Idx_f - AA_sorted[i][0] > AA_sorted[i][0] - Idx_i:
        AnsIdx[AA_sorted[i][0]] = Idx_f
        #answer += abs(AA_sorted[i][0]-Idx_f)*AA_sorted[i][1]
        Idx_f -= 1
    else:
        AnsIdx[AA_sorted[i][0]] = Idx_i
        #answer += abs(AA_sorted[i][0]-Idx_i)*AA_sorted[i][1]
        Idx_i += 1
    #print(AA_sorted[i][0],Idx_i,Idx_f)
for i in range(N):
    answerb += abs(AAwIdx[i][0] - AnsIdx[i])*AAwIdx[i][1]
#print(AnsIdx)
print(max(answer, answerb))

Submission status: Runtime Error

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

left = 0
right = N-1
pos_and_a = list(sorted(enumerate(a_s), key=lambda x: -(x[1] * max(x[0]-left, right-x[0]))))

def inner(pos_and_a, total, left, right):
  if not pos_and_a:
    return total
  pos_and_a = list(sorted(pos_and_a, key=lambda x: -(x[1] * max(x[0]-left, right-x[0]))))
  past_pos, a = pos_and_a[0]
  del pos_and_a[0]
  dist_left = abs(past_pos - left) 
  dist_right = abs(right - past_pos)
  return max(inner(pos_and_a[:], total + a * dist_left, left+1, right), 
             inner(pos_and_a[:], total + a * dist_right, left, right-1))

print(inner(pos_and_a, 0, left, right))

Submission status: Runtime Error

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

import math
from itertools import permutations

lis = [0]*N
for i in range(N):
    lis[i] = i

num = math.factorial(N)

scores = [0]*num
i = 0
for v in permutations(lis, N):
    score = 0
    for j in range(N):
        score += abs(v.index(j)-j) * A[j]
    scores[i] = score
    i += 1

print(max(scores))

Submission status: Runtime Error

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

ans = []
for i in range(n):
    temp = np.array([a[i] * abs(i - j) for j in range(n)])
    ans.append([temp.max(), temp])

ans = sorted(ans)[::-1]
mem = np.array([True for i in range(n)])

total = 0
for x, ai in ans:
    ai[np.logical_not(mem)] = 0
    total += ai.max()    
    mem[ai.argmax()] = False
print(total)

Submission status: Runtime Error

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

AA=[]
for i in range(N):
    AA.append([A[i],i])
AA.sort(reverse=True)

f=0
l=N-1
ans=0

for j in range(N):
    if abs(AA[j][1]-f)>abs(l-AA[j][1]):
        ans+=AA[j][0]*abs(AA[j][1]-f)
        f+=1
    elif:
        ans+=AA[j][0]*abs(l-AA[j][1])
        l-=1
print(ans)

Submission status: Runtime Error

Solution code:
from heapq import *
import sys
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import time
import math
def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))
N=int(input())
A=list(map(int,input().split()))
A=[[A[i],i] for i in range(N)]
A.sort()
c=0
for i in range(N//2):
    a1,i1=A.pop()
    a2,i2=A.pop()
    b=(N-1-i)
    c+=max(a1*round(abs(i-i1))+a2*round(abs(b-i2)),a1*round(abs(b-i1))+a2*round(abs(i-i2)))
if N%2:
    a1,i1=A.pop()
    b=(N-1)//2
    c+=ai*round(abs(b-i1))
print(c)

Submission status: Runtime Error

Solution code:
import math
n = int(input())
dat = list(map(int, input().split()))
#dat = [[i, datSource[i]] for i in range(n)]
#dat.sort(key=lambda x: (-x[1], -x[0]))
indL = 0
indR = n - 1


loop = math.ceil(n / 2)
used = [False] * n # その数は使ったか？
filled = [False] * n # 埋まっているか？
res = 0
while indR >= indL:
    # まずL
    maxindL = -1
    maxvalL = -9999999999999999999999
    maxindR = -1
    maxvalR = -9999999999999999999999

    for ind in range(n):
        if used[ind]: # もう使っているならパス
            continue
        disL = abs(ind - indL)
        if (dat[ind] * disL) > maxvalL:
            maxvalL = dat[ind] * disL
            maxindL = ind
        disR = abs(ind - indR)
        if (dat[ind] * disR) > maxvalR:
            maxvalR = dat[ind] * disR
            maxindR = ind

    if maxindR == maxindL:
        if maxvalL >= maxindR: # L > R
            filled[indL] = True
            used[maxindL] = True
            res += maxvalL
            #print("L:", indL, "maxind", maxindL, "maxval", maxvalL)
            indR = r + i
            maxindR = -1
            maxvalR = -9999999999999999999999
            for ind in range(n):
                if used[ind]: # もう使っているならパス
                    continue
                disR = abs(ind - indR)
                if (dat[ind] * disR) > maxvalR:
                    maxvalR = dat[ind] * disR
                    maxindR = ind
            filled[indR] = True
            used[maxindR] = True
            res += maxvalR
            #print("R:", indR, "maxind",maxindR, "maxval",maxvalR)
        else: # R < L
            filled[indR] = True
            used[maxindR] = True
            res += maxvalR
            #print("R:", indR, "maxind",maxindR, "maxval",maxvalR)
            maxindL = -1
            maxvalL = -9999999999999999999999
            for ind in range(n):
                if used[ind]:  # もう使っているならパス
                    continue
                disL = abs(ind - indL)
                if (dat[ind] * disL) > maxvalL:
                    maxvalL = dat[ind] * disL
                    maxindL = ind
            filled[indL] = True
            used[maxindL] = True
            res += maxvalL
            #print("L:", indL, "maxind", maxindL, "maxval", maxvalL)
    else:
        filled[indL] = True
        used[maxindL] = True
        res += maxvalL
        #print("L:", indL, "maxind",maxindL, "maxval",maxvalL)
        filled[indR] = True
        used[maxindR] = True
        res += maxvalR
        #print("R:", indR, "maxind",maxindR, "maxval",maxvalR)
    indL += 1
    indR -= 1

print(res)

Submission status: Runtime Error

Solution code:
from heapq import *
import sys
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import time
import math
def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))
N=int(input())
A=list(map(int,input().split()))
A=[[A[i],i] for i in range(N)]
A.sort()
c=0
for i in range(N//2):
    a1,i1=A.pop()
    a2,i2=A.pop()
    b=(N-1-i)
    c+=max(a1*round(abs(i-i1))+a2*round(abs(b-i2)),a1*round(abs(b-i1))+a2*round(abs(i-i2)))
if A:
    a1,i1=A.pop()
    b=(N-1)//2
    c+=ai*round(abs(b-i1))
print(c)

Submission status: Runtime Error

Solution code:
N = int(input())
A = list(map(int, input().split()))
ans = 0

def get_score(N, A, fixed_, i_, score_):
    global ans
    score = score_
    i = i_
    fixed = fixed_[:]
    self = A[i]
    for x in range(i,N):
        if x in fixed_:
            continue
        elt = A[x]
        fixed += x, i,
        score += (elt + self) * abs(i-x)
        while i in fixed:
            i += 1
        if i < N:
            get_score(N, A, fixed, i, score)
        else:
            ans = max(ans, score)
        fixed = fixed_[:]
        i = i_
        score = score_
        
        
        
get_score(N, A, [], 0, 0)
print(ans)

Submission status: Runtime Error

Solution code:
N = int(input())
A = []
B = []
yorokobi = []
for i in range(N):
    A.append(map(int,input().split()))
    B.append(A[i])
for i in range(N):
    if A.index(max(B)) == 0:
       continue
    else:
        yorokobi.append(A[i] * (A.index(max(B)) - A[i]))
        A[A.index(max(B))],A[i] = A[i],A[A.index(max(B))]
        B.remove(B.index(max(B)))
print(sum(yorokobi))

Submission status: Runtime Error

Solution code:
import sys
stdin = sys.stdin
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
a = na()
b = []
for i in range(n):
    b.append((a[i],i))

b.sort(reverse=True)

ans = 0

def f(left,right,k,c):
    if k == n:
        return c
    i,j = b[k]
    x = abs(j-left)
    y = abs(right-j)
    return max(f(left+1,right,k+1,c+x*i), f(left,right-1,k+1,c+y*i))

ans = f(0,n-1,0,0)

print(ans)

Submission status: Runtime Error

Solution code:
import sys
stdin = sys.stdin
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
a = na()
b = []
for i in range(n):
    b.append((a[i],i))

b.sort(reverse=True)

ans = 0

def f(left,right,k,c):
    if k == n:
        return c
    i,j = b[k]
    x = j-left
    y = right-j
    return max(f(left+1,right,k+1,c+x*i), f(left,right-1,k+1,c+y*i))

ans = f(0,n-1,0,0)

print(ans)

Submission status: Runtime Error

Solution code:
def valMove(i,val):
	global farR
	global farL
	left = abs(farR-i)
	right = abs(farL-i)
	return max(val*right,val*left)

# py abc163e.py
# n = int(input())
# arr = list(map(int,input().split()))
n = 
arr = [1,3,4,2]
moved = {}
for i in range(n):
	moved[i] = False

farR = n-1
farL = 0

ans = 0

while True:
	toMove = -1
	for i in range(n):
		if not moved[i]:
			toMove = i
			moved[i] = True
			break
	if (toMove == -1):
		break

	direction = -1
	if abs(farR - toMove) > abs(farL - toMove):
		direction = 1 #right
	else:
		direction = 0 #left

	for i in range(n):
		if valMove(toMove,arr[toMove]) < valMove(i,arr[i]):
			toMove = i
			if abs(farR - toMove) > abs(farL - toMove):
				direction = 1 #right
			else:
				direction = 0 #left

	ans+= valMove(toMove,arr[toMove])
	arr[toMove] = -1
	if direction == 1:
		farR-=1
	else:
		farL+=1

print(ans)

Submission status: Runtime Error

Solution code:
import sys
stdin = sys.stdin
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
a = na()
b = []
r = [0]
for i in range(n):
    b.append((a[i],i))
for i in a:
    r.append(r[-1]+i)

b.sort(reverse=True)

ans = 0

def f(left,right,k,c):
    if k == n:
        return c
    i,j = b[k]
    p = r[j]
    q = r[n]-r[j+1]
    x = (j-left)*i
    y = (right-j)*i
    if x >= 0 and x+p >= y+q:
        return f(left+1, right, k+1, c+x)
    else:
        return f(left, right-1, k+1, c+y)

ans = f(0,n-1,0,0)

print(ans)

Submission status: Runtime Error

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

left = 0
right = N-1
pos_and_a = list(sorted(enumerate(a_s), key=lambda x: -(x[1] * max(x[0]-left, right-x[0]))))

def inner(pos_and_a, total, left, right):
  if not pos_and_a:
    return total
  pos_and_a = list(sorted(pos_and_a, key=lambda x: -(x[1] * max(x[0]-left, right-x[0]))))
  past_pos, a = pos_and_a[0]
  del pos_and_a[0]
  dist_left = abs(past_pos - left) 
  dist_right = abs(right - past_pos)
  if dist_left == dist_right:
  	return max(inner(pos_and_a, total + a * dist_left, left+1, right), 
    		   inner(pos_and_a, total + a * dist_right, left, right-1))
  if dist_left > dist_right:
    return inner(pos_and_a, total + a * dist_left, left+1, right)
  return inner(pos_and_a, total + a * dist_right, left, right-1) 

print(inner(pos_and_a, 0, left, right))

Submission status: Runtime Error

Solution code:
N=int(input())
A=list(map(int,input().split()))
def f(p):
    if not p:
        return 0
    i=N-len(p)
    return max([f(p-set([j]))+A[i]*abs(i-j) for j in p])
p=set(range(N))
print(f(p))

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
sys.setrecursionlimit(10**9)

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

a2 = []
for i in range(n):
    a2.append((a[i], i))
a2.sort(reverse=True)

dp = np.full((n, n, n), -1)


def solve(i2, s, e):
    if dp[i2][s][e] != -1:
        return dp[i2][s][e]

    a, i = a2[i2]

    if i2 == n-1:
        dp[i2][s][e] = a * abs(s-i)
        return dp[i2][s][e]

    dp[i2][s][e] = max(solve(i2+1, s+1, e) + a * abs(s - i),
                       solve(i2+1, s, e-1) + a * abs(e - i))

    return dp[i2][s][e]


print(solve(0, 0, n-1))

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
sys.setrecursionlimit(10**10)

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

a2 = []
for i in range(n):
    a2.append((a[i], i))
a2.sort(reverse=True)

dp = np.full((n, n, n), -1)


def solve(i2, s, e):
    if dp[i2][s][e] != -1:
        return dp[i2][s][e]

    a, i = a2[i2]

    if i2 == n-1:
        dp[i2][s][e] = a * abs(s-i)
        return dp[i2][s][e]

    dp[i2][s][e] = max(solve(i2+1, s+1, e) + a * abs(s - i),
                       solve(i2+1, s, e-1) + a * abs(e - i))

    return dp[i2][s][e]


print(solve(0, 0, n-1))

Submission status: Runtime Error

Solution code:
import numpy as np

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

a = np.array(a, dtype=int)


def go(left, right, nm):
    if left > right:
        return 0
    i = np.argmax(nm*a)
    x = a[i]
    new_nm = nm.copy()
    new_nm[i] = False

    to_left = np.abs(i - left)
    to_right = np.abs(right - i)
    rtn_left = x * to_left + go(left+1, right, new_nm) 
    rtn_right = x * to_right + go(left, right-1, new_nm) 
    return max(rtn_left, rtn_right)

not_moved = np.ones_like(a)
rtn = go(0, n-1, not_moved)
print(rtn)

Submission status: Runtime Error

Solution code:
import sys
stdin = sys.stdin
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
a = na()
b = []
r = [0]
for i in range(n):
    b.append((a[i],i))
for i in a:
    r.append(r[-1]+i)

b.sort(reverse=True)

ans = 0

def f(left,right,k,c):
    if k == n:
        return c
    i,j = b[k]
    p = r[j]
    q = r[n]-r[j+1]
    x = (j-left)*i+p
    y = (right-j)*i+q
    if x >= y:
        return f(left+1,right,k+1,c+(j-left)*i)
    elif x < y:
        return f(left,right-1,k+1,c+(right-j)*i)

ans = f(0,n-1,0,0)

print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np

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

a = np.array(a, dtype=int)


def go(left, right, nm):
    if left > right:
        print(nm)
        return 0
    i = np.argmax(nm*a)
    x = a[i]
    new_nm = nm.copy()
    new_nm[i] = False

    to_left = np.abs(i - left)
    to_right = np.abs(right - i)
    rtn_left = x * to_left + go(left+1, right, new_nm) 
    rtn_right = x * to_right + go(left, right-1, new_nm) 
    return max(rtn_left, rtn_right)

not_moved = np.ones_like(a)
rtn = go(0, n-1, not_moved)
print(rtn)

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
sys.setrecursionlimit(10**8)

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

a2 = []
for i in range(n):
    a2.append((a[i], i))
a2.sort(reverse=True)

dp = np.full((n, n, n), -1)


def solve(i2, s, e):
    if dp[i2][s][e] != -1:
        return dp[i2][s][e]

    a, i = a2[i2]

    if i2 == n-1:
        dp[i2][s][e] = a * abs(s-i)
        return dp[i2][s][e]

    dp[i2][s][e] = max(solve(i2+1, s+1, e) + a * abs(s - i),
                       solve(i2+1, s, e-1) + a * abs(e - i))

    return dp[i2][s][e]


print(solve(0, 0, n-1))

Submission status: Runtime Error

Solution code:
# 整数を一つ入力
N = int(input())
# スペース区切りの整数をリストに入力
t = [int(x) for x in input().split()]

A = []
for i in range(N):
    A.append([t[i],i+1])

A.sort(reverse=True)

r_max = 0

def test(i,r,h,l):
    global r_max
    if i == N-1:
        r_max = max(r_max, r+abs(A[i][1]-h)*A[i][0])
    else:
        test(i+1,r+abs(A[i][1]-h)*A[i][0],h-1,l)
        test(i+1,r+abs(A[i][1]-l)*A[i][0],h,l+1)

test(0,0,N,1)

print(r_max)