#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 100010;
int n;
ll m, ans = 1000000000000000000ll;
ll a[N];
struct bit {
	ll tree[N * 2];
	inline int lowbit(int i)
	{
		return i & -i;
	}
	void update(int pos, int num)
	{
		for(int i = pos; i <= 2 * m; i += lowbit(i)) 
			tree[i] += num;
	}
	ll query(int pos)
	{
		ll ret = 0;
		for(int i = pos; i; i -= lowbit(i)) 
			ret += tree[i];
		return ret;
	}
} t1, t2;
int main()
{
	scanf("%d%lld", &n, &m);
	for(int i = 1; i <= n; ++i) scanf("%lld", &a[i]);
	ll now = a[1], all = 0, to;
	for(int i = 2; i <= n; ++i)
	{
		to = a[i] - 1;
		now = a[i - 1] - 1;
		if(to < now) to += m;
		all += to - now;
		t1.update(now + 1, now);
		t1.update(to + 1, - now);
		t2.update(now + 1, 1);
		t2.update(to + 1, - 1);	
	}
	for(int i = 1; i <= m; ++i)
	{
		ll sum1 = t1.query(i), sum2 = t2.query(i), sum = all;
		sum -= (ll)i * sum2 - sum1 - sum2;
		sum1 = t1.query(i + m); 
		sum2 = t2.query(i + m);
		sum -= (ll)(i + m) * sum2 - sum1 - sum2;
		ans = min(ans, sum);  
	}
	printf("%lld\n", ans);
	return 0;
}