n = int(input())
a  = list(map(int,input().split()))
res = []
for i in range(n):
    res.append((a[i],i))
res.sort(reverse = True)
lcnt,rcnt = 0,0
ans = 0
for val,ind in res:
    if ind-lcnt < n-ind-1-rcnt:
        
        ans +=val*(n-ind-1-rcnt)
        rcnt+=1
    else:
        ans +=val*(ind - lcnt)
        lcnt+=1
print(ans)
        
        
    
    