object Main extends App {

  import scala.io.StdIn._

  val n = readInt
  val heights = readLine.trim.split(' ').map(_.toInt).toList
  println(minCount(heights))
  def minCount(heights: List[Int], stack: List[Int] = List(0)): Int = {
    (heights, stack) match {
      case (h::t, s::_) if h > s ⇒ minCount(t, h::stack)
      case (h::t, s::_) if h == s ⇒ minCount(t, stack)
      case (h::_, f::s::r) if s > h ⇒ f - s + minCount(heights, s::r)
      case (h::t, f::r) ⇒ f - h + minCount(t, h::r)
      case (Nil, f::s::t) ⇒ f - s + minCount(Nil, s::t)
      case (Nil, s::Nil) ⇒ 0
      case (Nil, Nil) ⇒ ???
    }
  }

  implicit class Extension[T](val value :T) extends AnyVal {
    @inline
    def let[A](@inline func: T ⇒ A): A = func(value)
    @inline
    def also(@inline func: T ⇒ Unit): T = {func(value); value}
  }
}