def calc(a)
  return 0 if a.length == 0
  min = a.min
  a.map!{|i| i - min}
  next_list = []
  tmp_list = []
  a.each_with_index do |num,i|
    if i == a.length - 1
      tmp_list << num if num != 0
      next_list << tmp_list
    elsif num == 0
      next_list << tmp_list
      tmp_list = []
    else
      tmp_list << num
    end
  end
  return min + next_list.inject(0){|res,nl| res += calc(nl)}
end
n = gets.to_i
a = gets.chomp.split(' ').map(&:to_i)
puts calc(a)