#include <cstdio>
typedef long long ll;

#define N 200050
int a[N];
ll go[N],tc[N],mk[N];
int main()
{
	int n,m;scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
		scanf("%d",&a[i]);
		
	ll ans=0;
	for(int i=2;i<=n;i++)
	{
		if(a[i]<a[i-1]) a[i]+=m;
		ans+=a[i]-a[i-1];
		if(a[i]>=a[i-1]+2)
		{
			go[a[i-1]+2]++;
			go[a[i]+1]--;
			tc[a[i]+1]-=a[i]-a[i-1]-1;
		}
		if(a[i]>m) a[i]-=m;
	}
	
	ll res=0;
	for(int i=1;i<=m+m;i++)
	{
		go[i]+=go[i-1];
		res+=go[i]+tc[i];
		mk[i]=res;
	}
	
	ll maxgo=0;
	for(int i=1;i<=m;i++)
		if(mk[i]+mk[i+m]>maxgo)
			maxgo=mk[i]+mk[i+m];
	printf("%lld\n",ans-maxgo);
}