#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
int n, m, f[maxn], u[maxn], v[maxn], last[maxn];
int find(int x) {
  if (x == f[x]) return x;
  f[x] = find(f[x]);
  return f[x];
}
int main() {
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= n; i++) f[i] = i;
  for (int i = 1; i <= m; i++) {
    scanf("%d %d", &u[i], &v[i]);
    int fu = find(u[i]);
    int fv = find(v[i]);
    if (fu == fv) continue;
    if (fu > fv) swap(fu, fv);
    f[fu] = fv;
  }
  for (int i = 1; i <= n; i++) {
    f[i] = find(i);
    last[f[i]] = i;
  }
  int x = 0;
  int ans = 0;
  for (int i = 1; i <= n; i++) {
    int fa = find(i);
    for (int j = x + 1; j <= fa; j++) {
      int fu = find(j);
      int fv = find(i);
      if (fu == fv) continue;
      ans++;
      if (fu > fv)
        f[fv] = fu;
      else
        f[fu] = fv;
    }
    x = fa;
  }
  cout << ans << endl;
  return 0;
}
