let () = Scanf.scanf "%d %d\n" @@ fun k n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let ds = Array.init n @@ fun i -> (k + as_.((i + 1) mod n) - as_.(i)) mod k in
  Printf.printf "%d\n" @@ Array.fold_left ( + ) 0 ds - Array.fold_left max min_int ds