// 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 imos0 = new long[](m + 2);
    auto imos1 = new long[](m + 2);

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

        if (s < t) {
            imos0[1] += t - s;
            imos0[s + 1] -= t - s;

            imos0[s + 1] += t + 1;
            imos0[t + 1] -= t + 1;
            imos1[s + 1] -= 1;
            imos1[t + 1] += 1;

            imos0[t + 1] += t - s;
        }
        else {
            imos0[1] += t + 1;
            imos0[t + 1] -= t + 1;
            imos1[1] -= 1;
            imos1[t + 1] += 1;

            imos0[t + 1] += m - s + t;
            imos0[s + 1] -= m - s + t;

            imos0[s + 1] += t + m + 1;
            imos1[s + 1] -= 1;
        }

        debug {
            writeln("imos0:", imos0);
            writeln("imos1:", imos1);
        }
    }

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

    debug {
        writeln("imos0:", imos0);
        writeln("imos1:", imos1);
    }

    long ans = 1L * m * n;

    foreach (i ; 1 .. m + 1) {
        ans = min(ans, imos0[i] + imos1[i] * i);
    }

    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);
        }
    }
}