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

SUM = sum(A)

c = 0
MIN = 10 ** 13
f = -1
for i,a in enumerate(A):
    c += a
    dif = abs(SUM/2 - c)
    if MIN > dif:
        MIN = dif
        f = i 

L_d,R_d = [],[]
for i, a in enumerate(A[0:f+1]):
    L_d.append(tuple([a,i]))

for i, a in enumerate(A[f+1::]):
    R_d.append(tuple([a,i+f+1]))
L_d, R_d = sorted(L_d, reverse=True), sorted(R_d, reverse=True)

ans = 0
back = len(A) -1
count = 0
for k,v in L_d:
    ans += k * (back-v-count)
    count += 1
count =0
for k,v in R_d:
    ans += k * (v -count)
    count += 1

print(ans)