import scala.annotation.tailrec

object Main extends App {
  
  val sc = new java.util.Scanner(System.in)
  val N = sc.nextInt()
  val A = List.fill(N)(sc.nextLong())
  println(calc(0L, 0, 0L))
  
  @tailrec
  def calc(prev: Long, index: Int, acc: Long): Long = {
    if (index == A.length) {
      acc
    } else if (prev <= A(index)) {
      calc(A(index), index + 1, acc)
    } else {
      val diff = prev - A(index)
      calc(A(index) + diff, index + 1, acc + diff)
    }
  }

}
