#include <cstring>
#include <algorithm>
#include <cstdio>

using namespace std;
typedef long long ll;
const int MAXN = 100010;

int n, m, a[MAXN];

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

ll a1[MAXN] = {0}, d[MAXN] = {0};
void solve() {
	for( int i = 1; i < n; ++i ) {
		int dis = a[i] - a[i-1], now = a[i];
		if( dis < 0 ) dis += m;
		if( dis < now ) {
			a1[1] += dis;
			d[now-dis+1] += -1;
			d[now+1] -= -1;
			a1[now+1] += dis;
		} else {
			a1[1] += now;
			d[1] += -1;
			d[now+1] -= -1;
			a1[now+1] += dis;
			d[now-dis+m+1] += -1;
		}
	}
	ll now = 0, nd = 0, ans = 1e18;
	for( int i = 1; i <= m; ++i ) {
		now += nd, now += a1[i];
		ans = min( ans, now );
		nd += d[i];
	}
	printf( "%lld\n", ans );
}

int main() {
	input(), solve();
	return 0;
}
