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

// why am I so weak

int n, m;
int a[100055];

long long d[100055];
int have[100055];

int main() {
	scanf("%d %d", &n, &m);

	for (int i = 0; i < n; i++) {
		scanf("%d", &a[i]);
	}

	long long sum = 0;

	for (int i = 0; i + 1 < n; i++) {
		if (a[i + 1] > a[i]) {
			have[a[i] + 2]++, have[a[i + 1] + 1]--;
			d[a[i + 1] + 1] -= a[i + 1] - a[i] - 1;

			sum += a[i + 1] - a[i];
		} else {
			have[a[i] + 2]++, have[1]++;
			have[a[i + 1] + 1]--;

			d[a[i + 1] + 1] -= a[i + 1] + m - a[i] - 1;
			d[1] += m - a[i] - 1;

			sum += a[i + 1] + m - a[i];
		}
	}

	for (int i = 1; i <= m; i++) {
		have[i] += have[i - 1];
		d[i] += d[i - 1];
		d[i] += have[i];
	}

	printf("%lld\n", sum - *max_element(d, d + m + 1));

	return 0;
}
