#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

typedef long long ll;

int N, M;
vector<int> imos1;
vector<ll> imos2;
ll sum = 0;

int main(void) {
	cin >> N >> M;
	imos1.resize(2 * M + 1);
	imos2.resize(2 * M + 1);
	int a0;
	cin >> a0;
	for (int i = 1; i < N; ++i) {
		int a1;
		cin >> a1;
		if (a0 > a1)
			a1 += M;

		++imos1[a0];
		--imos1[a1];
		imos2[a0] += a0 - 1;
		imos2[a1] -= a0 - 1;

		sum += a1 - a0;
		a0 = a1;
		a0 %= M;
	}

	for (int i = 1; i < 2 * M; ++i) {
		imos1[i] += imos1[i - 1];
		imos2[i] += imos2[i - 1];
	}

	ll ans = sum;
	for (int i = 0; i < M; ++i) {
		int a = imos1[i];
		ll b = imos2[i];
		ll val = sum;
		val -= (ll)a * (ll)i - b - a;
		a = imos1[i + M];
		b = imos2[i + M];
		val -= (ll)a * (ll)(i + M) - b - a;
		ans = min(ans, val);
	}

	cout << ans << '\n';
	return 0;
}
