#C
import numpy as np

n = int(input())
a_ls = list(map(int, input().split()))
# n = 5
# a_ls = [2, 2, 2, 2, 2]
a_ls_new = []
a_ls_tmp = a_ls

while True:
  max_value = max(a_ls_tmp)
  max_index = a_ls_tmp.index(max_value)
  if max_index != 0:
    a_ls_new = a_ls_new + list(np.repeat(max_value, len(a_ls_tmp) - max_index))
    a_ls_tmp = a_ls_tmp[:max_index] 
  else:
    a_ls_new = a_ls_new + list(np.repeat(max_value, len(a_ls_tmp) - max_index))
    a_ls_tmp = a_ls_tmp[:max_index] 
    break

# print(a_ls_new)
print(sum(a_ls_new) - sum(a_ls))