def calc(a)
  return 0 unless a
  return a[0] if a.length == 1
  return a.max if a.length == 2
  min = a.min
  a.map!{|i| i - min}
  next_list = []
  s = 0
  a.each_with_index do |num,i|
    if num == 0
      next_list << a[s..i - 1] if s < i
      s = i + 1
    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)
