#include <bits/stdc++.h>
typedef long long int LL;
using namespace std;

const int N   = 2e5+7;
const int MOD = 1e9+7;
const double eps = 1e-6;
#define rep(aa,bb,cc) for(int aa=(bb),ee=(cc);aa<ee;aa++)
/***********************************************/
int n, m, a[N];
LL p[N];

int main() {
    LL all = 0;
    scanf("%d%d", &n, &m);
    for(int i=0; i<n; ++i) scanf("%d", a+i);
    for(int i=1; i<n; ++i) {
        int l = a[i-1], r = a[i];
        if(l>r) r += m;
        all += r-l;
        if(r-l>1) {
            p[l+2] += 1;
            p[r+1] -= (r-(l+2)+1) + 1;
            p[r+2] += (r-(l+2)+1);
        }
    }
    for(int i=1; i<=2*m; ++i) p[i] += p[i-1];
    for(int i=1; i<=2*m; ++i) p[i] += p[i-1];

    LL ans = -1;
    for(int i=1; i<=m; ++i) ans = max(ans, p[i]+p[i+m]);
    cout << all - ans << endl;

    return 0;
}
