let makeStools heights =
    let mutable stools = []

    let rec makeStoolsRec prev heights =
        match heights with
        | [] -> ()
        | head :: tail ->
            let stool =
                match prev <= head with
                | true -> 0L
                | false -> prev - heights.[0]

            stools <- stool :: stools

            makeStoolsRec (heights.[0] + stool) tail

    makeStoolsRec 0L heights

    stools

stdin.ReadLine() |> ignore

stdin.ReadLine().Split()
|> Seq.map int64
|> Seq.toList
|> makeStools
|> List.sum
|> printfn "%d"
