#5_numpy で最後は計算
import numpy as np

int_n = int(input())
list_x = list(map(int, input().split()))
 

list_x_left = list_x
list_calc_minus = list()
 
while len(list_x_left) != 0:
  
  int_list_x_prosess_len = len(list_x_left) - list_x_left.index(max(list_x_left))
  int_max_list_x_prosess = max(list_x_left)
  list_x_left = list_x_left[:list_x_left.index(max(list_x_left))]
  
  [list_calc_minus.insert(0, int_max_list_x_prosess) for i in range(int_list_x_prosess_len)]
  
#print(sum([x - y for (x, y) in zip(list_calc_minus, list_x)]))

print((np.array(list_calc_minus) - np.array(list_x)).sum())
 