#include <bits/stdc++.h>
using namespace std;
inline void read(int &x) {
  x = 0;
  int f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  x *= f;
}
inline void judge() {
  freopen("in.txt", "r", stdin);
  freopen("out.txt", "w", stdout);
}
const int maxn = 100005;
long long f[maxn], g[maxn];
int n, m, a, b;
int main() {
  read(n);
  read(m);
  read(a);
  long long sum = 0, ans = 1e18;
  for (int i = (1); i <= (n - 1); i++) {
    read(b);
    sum += b - a;
    f[a + 1] += a + 1;
    f[b + 1] -= a + 1;
    g[a + 1]++;
    g[b + 1]--;
    if (a > b) {
      sum += m;
      f[1] += a + 1 - m;
      f[b + 1] += m;
      g[1]++;
    }
    a = b;
  }
  ans = sum;
  for (int i = (1); i <= (m); i++) {
    f[i] += f[i - 1];
    g[i] += g[i - 1];
    ans = min(ans, sum + f[i] - g[i] * i);
  }
  cout << ans << endl;
  return 0;
}
