N = gets.to_i
h = gets.split.map(&:to_i)

def calc(h)
  puts "h: #{h.inspect}"
  if h.size > 1
    m = h.min

    ret = []
    needle = 0
    h = h.map {|e| e - m}
    h.each_with_index do |e, i|
      if e == 0 || i == (h.size - 1)
        ret << h[needle..i].select{|elm| elm != 0}.uniq if h[needle..i].select{|elm| elm != 0} != []
        needle = i+1
      end
    end
    m + ret.map {|a| calc(a)}.inject(&:+)
  else
    h.min
  end
end

puts calc(h)