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

ans = 0

while True:
    key = A.index(max(A))
    zennhann = A[:key]
    kouhann = A[key:]
    ans += max(A)*(len(A)-key) - sum(kouhann)    
    A = zennhann
    
    if len(A) == 0:
        break

print(ans)