#include<bits/stdc++.h>
using namespace std;
 
const int M = 3e5 + 10;
long long cnt[M];
int op[M];
 
int main()
{
	memset(cnt, 0, sizeof(cnt));
	int n, m;
	long long totl = 0;
	scanf("%d%d", &n, &m);
	for(int i=0; i<n; ++i)
		scanf("%d", op + i);
	for(int i=1; i<n; ++i) {
		int l = op[i-1], r = op[i];
		if(l > r) r += m;
		totl += r - l;
		if(r - l > 1) {
			++cnt[l+2];
			 cnt[r+1]-=(r-(l+2) +1)+1;
			 cnt[r+2]+=(r-(l+2)+1);
		}
	}
	for(int i=1; i<=2*m; ++i) {
		cnt[i] += cnt[i-1];
	}
	for(int i=1; i<=2*m; ++i) {
		cnt[i] += cnt[i-1];
	}
	long long ans = -1;
	for(int i=1; i<=m; ++i) {
		ans = max(cnt[i] + cnt[i+m], ans);
	}
	cout<<totl - ans<<endl;
	return 0;
}