#!python3

# input
N = int(input())
A = list(map(int, input().split()))


def main():
    P = [(A[i], i) for i in range(N)]
    P.sort(reverse=True)

    left, right = 0, N - 1
    ans = 0
    for x, i in P:
        A[i] = 0
        t = (right - i) * x - (i - left) * x
        t += sum(A[i:])
        t -= sum(A[:i])
        if t > 0:
            ans += (right - i) * x
            right -= 1
        else:
            ans += (i - left) * x
            left += 1
    
    print(ans)


if __name__ == "__main__":
    main()
