N=int(input())
A=B=list(map(int,input().split()))
s=j=N+1
sum_A=0

if A==sorted(A):
    print(0)
    exit()

for i in range(1,N):
    x=max(B[:s])
    s=B.index(x)
    B[s:j]=[x]*len(B[s:j])
    j=s
    if s==0:
        break
    
print(sum(B)-sum(A))