x = int(input())

line = [int(x) for x in input().split()]

dic = {}

for i in range(0, x):
    if dic.get(line[i]) != None:
        dic[line[i]].append(i)
    else:
        dic[line[i]] = [i]


availL = 0
availR = x-1

temp = sorted(line, reverse = True)

total = 0

for i in temp:
    a1 = min(dic[i])
    a2 = max(dic[i])

    v1 = abs(availL-a2)
    v2 = abs(availR-a1)

    if v1 > v2:
        #print(str(i) + " who was from "+ str(a2)+ " goes to " + str(availL))
        total = total + (v1*i)
        availL = availL + 1
        dic[i].remove(a2)
    else:
        #print(str(i) + " who was from "+ str(a1)+ " goes to " + str(availR))
        total = total + (v2*i)
        availR = availR - 1
        dic[i].remove(a1)

print(total)
