let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let acc = Array.make (2 * m + 1) 0 in
  for i = 0 to n - 2 do
    let a = as_.(i) in
    let b = as_.(i + 1) + if as_.(i) <= as_.(i + 1) then 0 else m in
    acc.(a + 1) <- acc.(a + 1) + 1;
    acc.(b) <- acc.(b) - 1
  done;
  for i = 0 to 2 * m - 1 do
    acc.(i + 1) <- acc.(i) + acc.(i + 1)
  done;
  for i = 0 to n - 2 do
    let a = as_.(i) in
    let b = as_.(i + 1) + if as_.(i) <= as_.(i + 1) then 0 else m in
    acc.(b) <- acc.(b) - b + a + 1
  done;
  for i = 0 to 2 * m - 1 do
    acc.(i + 1) <- acc.(i) + acc.(i + 1)
  done;
  for i = m to 2 * m - 1 do
    acc.(i - m) <- acc.(i) + acc.(i - m)
  done;
  Printf.printf "%d\n" @@
  Array.fold_left ( + ) 0
    (Array.init (n - 1) (fun i -> (m + as_.(i + 1) - as_.(i)) mod m))
  - Array.fold_left max min_int (Array.sub acc 0 m)
