def group(xs)
  if xs[0] == 0
    group xs[1..-1]
  elsif xs.size == 0
    []
  else
    g = []
    rest = []
    xs.size.times {|i|
      if xs[i] != 0
        g << xs[i]
      else
        rest = xs[i+1..-1]
        break
      end
    }
    [g] + group(rest)
  end
end

def sum(xs)
  if xs.size > 0
    xs.inject :+
  else
    0
  end
end

def solve(g)
  m = g.min
  gs = group(g.map{|x| x - m})
  m + sum(gs.map{|h| solve(h)})
end

_ = gets.to_i
xs = gets.split.map(&:to_i)
p sum(group(xs).map{|g| solve(g)})
