import numpy as np
N = int(input())
As = np.array(list(map(int, input().split())))

origs = As.copy()
idxs = np.argsort(origs)[::-1]
head, tail = 0, N - 1

res = 0
#tmp = np.zeros(N)
for idx in idxs:
    ai = origs[idx]
    ptl = ai * (idx - head)
    ptr = ai * (tail - idx)
    sumr = origs[idx+1:].sum()
    suml = origs[:idx].sum()
    if (ptr - suml) > (ptl - sumr):#右に行くとお得
        #tmp[tail] = ai
        tail -= 1
        res += ptr
    else:
        #tmp[head] = ai
        head += 1
        res += ptl
    origs[idx] = 0
    #sys.exit()
print(res)