"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}

var myOut = main();
if(myOut !== undefined)console.log(myOut);

function main(){
  var n = next(), m = next();
  var a = nexts(n);
  var b = xArray(0,m*2+3);
  var sum = 0;
  for(var i = 1; i < n; i++){
    var c = a[i-1], d = a[i];
    if(d < c)d += m;
    var x = d-c;
    b[c+2]--, b[d+1] += x, b[d+2] -= x-1;
    sum += x;
  }
  var tot = 0;
  for(var i = 2; i < m*2+1; i++){
    tot += b[i];
    b[i] = b[i-1] + tot;
  }
  var ans = sum;
  for(var i = 1; i <= m; i++){
    var t = sum + b[i] + b[i+m];
    if(t < ans)ans = t;
  }
  return ans;
}