#include <bits/stdc++.h>
using namespace std;
bool comp(pair<int, int> in1, pair<int, int> in2) {
  if (in1.second < in2.second) {
    return true;
  } else {
    return false;
  }
}
int main() {
  int n, m;
  cin >> n >> m;
  int a[100100];
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  vector<pair<int, int> > c, b;
  for (int i = 1; i <= n - 1; i++) {
    pair<int, int> in;
    in.first = a[i];
    if (a[i] > a[i + 1]) {
      in.second = a[i + 1] + m;
    } else {
      in.second = a[i + 1];
    }
    b.push_back(in);
    c.push_back(in);
  }
  sort(b.begin(), b.end());
  sort(c.begin(), c.end(), comp);
  int minus[100100];
  for (int i = 0; i <= n; i++) {
    minus[i] = 0;
  }
  int contain = 0;
  for (int i = 0; i < n - 1; i++) {
    if ((b[i].first <= (m + 1 - 2)) && (b[i].second >= (m + 1))) {
      contain++;
      minus[1] += m - b[i].first;
    }
  }
  for (int i = 2; i <= m; i++) {
    int ok = n - 2;
    int ng = -1;
    while (ok - ng > 1) {
      int mid = (ok + ng) / 2;
      if (b[mid].first >= (i - 2)) {
        ok = mid;
      } else {
        ng = mid;
      }
    }
    while (b[ok].first == (i - 2)) {
      contain++;
      ok++;
    }
    ok = n - 2;
    ng = -1;
    while (ok - ng > 1) {
      int mid = (ok + ng) / 2;
      if (c[mid].second >= (i - 1)) {
        ok = mid;
      } else {
        ng = mid;
      }
    }
    while (c[ok].second == (i - 1)) {
      contain--;
      minus[i] -= (c[ok].second - c[ok].first - 1);
      ok++;
    }
    ok = n - 2;
    ng = -1;
    while (ok - ng > 1) {
      int mid = (ok + ng) / 2;
      if (c[mid].second >= (i - 1 + m)) {
        ok = mid;
      } else {
        ng = mid;
      }
    }
    while (c[ok].second == (i - 1 + m)) {
      contain--;
      minus[i] -= (c[ok].second - c[ok].first - 1);
      ok++;
    }
    minus[i] += minus[i - 1] + contain;
  }
  int sum = 0;
  for (int i = 0; i < n - 1; i++) {
    sum += b[i].second - b[i].first;
  }
  int minimum = minus[1];
  for (int i = 2; i <= m; i++) {
    minimum = max(minimum, minus[i]);
  }
  cout << sum - minimum << endl;
  return 0;
}
