Scanf.scanf "%d" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
    let rec loop i expect acc =
        if i = 0 then (if expect = 0 then acc else -1) else
            if a.(i) < expect then -1 else
                loop (i - 1) (max 0 (a.(i) - 1)) (if expect = a.(i) then acc else acc + a.(i))
    in
    loop (n - 1) 0 0 |> Printf.printf "%d\n"
)