#include <bits/stdc++.h>

typedef long long ll;
const int N = 100054;

int n, p;
int a[N];
ll I = 0, r[N];

void handle(int s, int t) {
	assert(s != t);
	if (s + 1 == t || s + 1 == t + p) return;
	int _;
	if (s < t) --r[s + 2], r[t + 1] += t - s, r[t + 2] += s - t + 1;
	else _ = p - s - 1, --r[s + 2], *r -= _, r[1] += _ - 1, r[t + 1] += t - s + p, r[t + 2] += s - t + 1 - p;
}

int main() {
	int i;
	scanf("%d%d", &n, &p);
	for (i = 0; i < n; ++i) scanf("%d", a + i), --a[i];
	for (i = 1; i < n; ++i)
		I += (a[i] - a[i - 1] + p) % p, handle(a[i - 1], a[i]);
	for (i = 1; i < p; ++i) r[i] += r[i - 1];
	for (i = 1; i < p; ++i) r[i] += r[i - 1];
	printf("%lld\n", I + *std::min_element(r, r + p));
	return 0;
}