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

ll a[100000];
ll t[100010];
ll add[100010];
ll s[100010];

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

	int n, m;
	cin >> n >> m;

	for(int i = 0; i < n; i++) {
		cin >> a[i];
		a[i]--;
	}

	for(int i = 0; i < n - 1; i++) {
		if(a[i] < a[i + 1]) {
			int minC = abs(a[i] - a[i + 1]);
			t[0] += minC;
			t[a[i + 1] + 1] += minC;
			add[a[i + 1] + 1] += 1;
			add[a[i] + 1] -= 1;
		}
		else {
			int minC = m + a[i + 1] - a[i];
			int x = minC - (m - 1 - a[i]);
			t[0] += x;
			t[a[i + 1] + 1] += minC;
			add[0] -= 1;
			add[a[i + 1] + 1] += 1;
			add[a[i] + 1] -= 1;
		}
	}

	ll sum = 0, addsum = 0;
	ll ans = 1LL << 60;
	for(int i = 0; i < m; i++) {
		sum += t[i] + addsum;
		addsum += add[i];
		//cerr << sum << endl;
		s[i] = sum;
		ans = min(ans, sum);
	}
	cout << ans << endl;
}
