#include<bits/stdc++.h>
#define rep(i,n)for(int i=0;i<(n);i++)
using namespace std;
typedef long long ll;

int a[100000], n, m;
ll sum[300000], sum2[300000];

int dist(int a, int b, int c) {
	return min((b + m - a) % m, (b + m - c) % m + 1);
}
int main() {
	scanf("%d%d", &n, &m);
	rep(i, n)scanf("%d", &a[i]), a[i]--;
	rep(i, n - 1) {
		sum[a[i] + 1]++;
		if (a[i] < a[i + 1]) {
			sum[a[i + 1] + 1]--;
			sum2[a[i + 1] + 1] -= a[i + 1] - a[i];
		}
		else {
			sum[a[i + 1] + m + 1]--;
			sum2[a[i + 1] + m + 1] -= a[i + 1] + m - a[i];
		}
	}
	for (int i = 1; i < m * 2; i++) {
		sum[i] += sum[i - 1];
		sum2[i] += sum2[i - 1] + sum[i];
		if (i >= m)sum2[i - m] += sum2[i];
	}
	ll ans = 0;
	int id = max_element(sum2, sum2 + m) - sum2;
	rep(i, n - 1) {
		ans += dist(a[i], a[i + 1], id);
	}
	printf("%lld\n", ans);
}