local n, m = io.read("*n", "*n")
local t = {}
for i = 1, n do
  t[i] = io.read("*n")
end
local bias, velocity = {}, {}
for i = 1, m + 2 do
  bias[i], velocity[i] = 0, 0
end
for i = 1, n - 1 do
  local src, dst = t[i], t[i + 1]
  if src < dst then
    local len = dst - src
    bias[1] = bias[1] + len
    velocity[src + 2] = velocity[src + 2] - 1
    velocity[dst + 2] = velocity[dst + 2] + 1
    bias[dst + 1] = bias[dst + 1] + len
  else
    local len = dst + m - src
    bias[1] = bias[1] + dst + 1
    velocity[1] = velocity[1] - 1
    velocity[dst + 2] = velocity[dst + 2] + 1
    bias[dst + 1] = bias[dst + 1] + len
    velocity[src + 2] = velocity[src + 2] - 1
  end
end
local ret = 0
local b, v = 0, 0
for i = 1, m do
  v = v + velocity[i]
  b = b + bias[i] + v
  if i == 1 then ret = b
  else ret = math.min(ret, b)
  end
end
print(ret)
