open Printf
open Scanf

let solve n =
  let aa = Array.init n @@ fun _ -> scanf "%d " @@ fun x -> x in
  let f (tc, mh) a = if mh <= a then (tc, a) else (tc + mh - a, mh) in
  fst @@ Array.fold_left f (0, 0) aa

let () =
  scanf "%d " solve |> printf "%d\n"
