#!/usr/local/bin/python3
N = int(input())
A = list(map(int, input().split()))[::-1]
 
ans = 0
m = A[0]
s = n = 0
for i in range(N):
    if A[i] <= m:
        ans += n*m - s
        s = n = 0
    m = A[i]
    s += A[i]
    n += 1
    print(f"result: {m}, {n}, {s}, {ans}")
if A[i] <= m:
    ans += n*m - s

print(ans)