//A,Elebereth Gilthoniel mantae!
//For Temeria!
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<vector>
#include<set>
#include<cstdio>
#include<map>
#include<stack>
#include<queue>
#include<cstring> 
using namespace std;
int ss[100008],kl[100008];
int oss,okl,ox;
int l[100008],r[100008];
int dp[100008];
int main()
{
 	//freopen("","r",stdin);
	//freopen("","w",stdout);
	int n,m;
	cin>>n>>m;
	cin>>r[0];
	for(int i=0;i<n-1;i++)
	{
		l[i+1]=r[i];cin>>r[i+1];
		int a=l[i+1],b=r[i+1];
		if(a>b) b+=m;
		oss+=b-a;
		ss[a+1]+=a+1;
		kl[a+1]++;
		ss[b+1]-=a+1;
		kl[b+1]--;
	}
	for(int i=1;i<=2*m;i++)
	{
		ss[i]+=ss[i-1];kl[i]+=kl[i-1];
		//cout<<i<<":"<<ss[i]<<" "<<kl[i]<<endl;
	}
	int ans=123465789;
	for(int i=1;i<=m;i++)
	{
		int ft=oss;
		ft+=ss[i];
		ft-=kl[i]*i;
		ft+=ss[i+m];
		ft-=kl[i+m]*(i+m);
		ans=min(ans,ft);//cout<<ft<<ans<<" ";
	}
	cout<<ans<<endl;
	return 0;
}
/*
4 6
1 5 1 4
*/