#include <bits/stdc++.h>
using namespace std;

typedef long long  LL;
int n,m,a[100010],b[100010],cnt;
LL ans,s;

bool cmp(int x,int y){return a[x]<a[y];}

void work()
{
	scanf("%d %d",&n,&m);
	for (int i=1; i<=n; i++)  scanf("%d",&a[i]),b[i]=i;
	sort(b+1,b+n+1,cmp);
	for (int i=1; i<n; i++)
		if (a[i]>a[i+1])  cnt++,s+=a[i+1];
		else  s+=a[i+1]-a[i];
	ans=s;
	for (int i=2,j=1; i<=m; i++)
		{
			s-=cnt;
			while ((j<=n)&&(a[b[j]]<i))
				{
					if (b[j]!=1)  cnt--,s+=(a[b[j]]-a[b[j]-1]+m)%m;
					if (b[j]!=n)  cnt++;
					j++;
				}
			ans=min(ans,s);
		}
	printf("%lld",ans);
}

int main()
{
	work();
	return 0;
}
