from collections import defaultdict
N = int(input())
A = [int(a) for a in input().split()]

ans = 0
memo = defaultdict(lambda: 0)

for i in range(1, len(A))[::-1]:
    memo[A[i]] += 1
    
    for h in list(memo.keys()):
        if (A[i-1] > h):
            diff = A[i-1] - h
            ans += diff * memo[h]
            # print(h, memo[h], diff)
            memo[h+diff] = memo[h]
            memo[h] = 0
            

    # print(memo)

print(ans)