n = int(input())
a = list(map(int,input().split()))
l = [[0,0]]
t = [0]
p = 0
m = max(a)
z = [0,n-1]
for i in range(n):
    p += a[i]
    l.append([p,0])
    if(t[-1] < a[i]):
        t.append(a[i])
    else:
        for j in range(len(t)):
            if(t[j] >= a[i]):
                if(t[j] > a[i]):
                    t.insert(j,a[i])
                break
for i in range(n):
    l[i][1] = p-l[i+1][0]
p = 0
for i in range(1,len(t)):
    temp = [x for x, val in enumerate(a) if val == t[-i]]
    for j in range(len(temp)):
        q = l[temp[j]] 
        if(q[0] > q[1]):
            for k in range(temp[j]):
                l[k][0] -= a[temp[j]]
            p += abs(temp[j]-z[0])*a[temp[j]]
            z[0] += 1
        else:
            for k in range(temp[j]+1,n):
                l[k][1] -= a[temp[j]]
            p += abs(temp[j]-z[1])*a[temp[j]]
            z[1] -= 1
print(p)