program guruguru
  implicit none
  integer :: n, m, a(100000), i, x
  integer(8) :: s, t, u, b(0:100000), c(100001)
  a = 0
  b = 0_8
  c = 0_8
  read(*,*) n, m
  read(*,*) a(1:n)
  s = 0_8
  do i = 1, n-1
    if (a(i+1).ge.a(i)) then
      s = s+int(a(i+1)-a(i),8)
      b(a(i+1)) = b(a(i+1))+int(a(i+1)-a(i),8)
      c(a(i)+1) = c(a(i)+1)+1_8
      c(a(i+1)) = c(a(i+1))-1_8
    else
      s = s+int(a(i+1),8)
      b(a(i+1)) = b(a(i+1))+int(a(i+1)+m-a(i),8)-1_8
      c(a(i)+1) = c(a(i)+1)+1_8
      c(1) = c(1)+1_8
      c(a(i+1)) = c(a(i+1))-1_8
    end if
  end do
  do i = 2, m
    c(i) = c(i)+c(i-1)
  end do
  u = s
  do x = 1, m-1
    t = u+b(x)-c(x)
    s = min(s,t)
    u = t
  end do
  write(*,'(i0)') s
  stop
end program guruguru