let n = Scanf.sscanf (read_line ()) "%d" @@ fun n -> n
let a = Array.to_list @@ Array.init n @@ fun _ -> int_of_string @@ read_line ()

let () =
  if List.hd a != 0 then print_endline "-1"
  else
    let (sum, _) = List.fold_left (fun (sum, before) i -> 
      (sum + (if i > before then i - before else i), i)
    ) (0, 0) @@ List.tl a in
    Printf.printf "%d\n" sum