let n = Int(readLine()!)!
let a = readLine()!.split(separator: " ").map { Int($0)! }

// var acc = 0
// var sub = 0

// for i in 1..<n {
//   sub = max(a[i - 1] + sub - a[i], 0)
//   acc = acc + sub
// }

let ans = a.reduce((0, 0, 0)) {
  let dif = max($0.1 + $0.2 - $1, 0)
  return ($0.0 + dif, dif, $1)
}

print(ans)
