class BIT():
    def __init__(self, n):
        self.size = n
        self.bit = [0] * (n + 1)

    def _sum(self, i):
        s = 0
        while i > 0:
            s += self.bit[i]
            i -= i & -i
        return s

    def add(self, i, val):
        i += 1
        while i <= self.size:
            self.bit[i] += val
            i += i & -i

    def get_sum(self, l, r):
        return self._sum(r) - self._sum(l)


n = int(input())
a = list(map(int, input().split()))
bit = BIT(n)
for i in range(n):
    bit.add(i, a[i])

a = [[a[i], i] for i in range(n)]
a = sorted(a, reverse=True)

l = 0
r = n - 1
ans = 0
for i in range(n):
    val, i = a[i]
    l_sum = bit.get_sum(0, i)
    r_sum = bit.get_sum(i + 1, n)
    l_sum += val * (i - l)
    r_sum += val * (r - i)
    if l_sum > r_sum:
        ans += val * (i - l)
        l += 1
    else:
        ans += val * (r - i)
        r -= 1
    bit.add(i, -val)
print(ans)