// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;

int n, m;
int[] a;

void main() {
    scan(n, m);
    a = readln.split.to!(int[]);

    auto imos = new int[](m + 2);
    auto b = new long[](m + 2);

    long move;

    foreach (i ; 0 .. n - 1) {
        int s = a[i], t = a[i + 1];

        if (s < t) {
            imos[s + 1]++;
            imos[t]--;
        }
        else {
            imos[1]++;
            imos[t]--;
            imos[s + 1]++;
        }

        b[t] += (t - s + m) % m - 1;

        move += min((a[i + 1] - a[i] + m) % m, 1 + (a[i + 1] - 1 + m) % m);
    }

    foreach (i ; 0 .. m) {
        imos[i + 1] += imos[i];
    }

    debug {
        writeln("move:", move);
    }

    long ans = move;

    foreach (i ; 1 .. m) {
        long tmp = move - imos[i] + b[i];
        ans = min(ans, tmp);
        move = tmp;

        debug {
            writeln("move:", move);
        }
    }

    writeln(ans);
}


void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}


void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}