from heapq import *
N = int(input())
A = list(map(int, input().split()))
work = []
for i in range(N):
    work.append([A[i], i])
work.sort(key=lambda x:x[0], reverse=True)
result = 0
left = 0
right = N-1
for a, i in work:
    temp1 = abs(i-left)
    temp2 = abs(right-i)
    sumright = sum(A[i+1:])
    sumleft = sum(A[:i])
    if temp1<temp2 and (sumleft<=a or sumright>=sumleft):
        result += temp2*a
        right -= 1
    else:
        result += temp1*a
        left += 1
print(result)