n = gets.to_i
flower = gets.split().map(&:to_i)
flower.push(0)
n = n * 1
ans = 0
max = 0
min = 0
flower.each do |f|
  if f > max
    max = f
  elsif f< min
    min = f
  elsif f < max
    ans += max - min
    min = f
    max = 0
  end
end
puts ans