#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int M=100005;
typedef long long LL;
template<class T>void Min(T &x,T y){
	if(x>y)x=y;
}
LL val[M],cnt[M];
int n,m,beg,x;
int main(){
	scanf("%d %d",&n,&m),n--;
	scanf("%d",&x);
	for(int i=1;i<=n;i++){
		scanf("%d",&beg);
		if(beg>x){
			val[1]+=beg-x,val[x+1]-=beg-x;
			if(beg<m)val[beg+1]+=beg-x;
			if(x+1<=beg)val[x+1]+=1+beg,val[beg+1]-=1+beg,cnt[x+1]++,cnt[beg+1]--;
		}else {
			val[beg+1]+=m-x+beg,val[x+1]-=m-x+beg;
			if(x<m)val[x+1]+=1+m+beg,cnt[x+1]++;
			val[1]+=1+beg,val[beg+1]-=1+beg,cnt[1]++,cnt[beg+1]--;
		}x=beg;
	}
	LL ans=val[1]-cnt[1]*1;
	for(int i=2;i<=m;i++)val[i]+=val[i-1],cnt[i]+=cnt[i-1],Min(ans,val[i]-i*cnt[i]);
	cout<<ans<<endl;
	return 0;
}