Scanf.(Array.(scanf " %d" @@ fun n ->
  let a = init n (fun _ -> scanf " %d" @@ fun v -> v) in
  let rec solve l r prev =
    let mn = ref a.(l) in
    for i=l to r do
      mn := min !mn a.(i)
    done;
    let mn = !mn in
    let res,tmpl,tmpr = ref [],ref l,ref (l-1) in
    for i=l to r do
      if a.(i) <> mn then (
        tmpr := !tmpr + 1;
      ) else (
        if !tmpr >= !tmpl then (
          res := (!tmpl,!tmpr) :: !res;
        );
        tmpl := i+1;
        tmpr := i;
      )
    done;
    if !tmpr >= !tmpl then
      res := (!tmpl,!tmpr) :: !res;
    List.fold_left (fun u (l,r) ->
      (* Printf.printf "%d,%d\n" l r; *)
      u + solve l r mn
    ) (mn - prev) !res
  in
  print_int @@ solve 0 (n-1) 0
))