#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
const long long mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-9;
int f[maxn], sum[maxn];
int find(int x) { return f[x] == x ? f[x] : f[x] = find(f[x]); }
int getsum(int x) { return sum[f[x] == x ? f[x] : f[x] = find(f[x])]; }
bool join(int u, int v) {
  int fu = find(u), fv = find(v);
  if (fu == fv) return 0;
  f[fu] = fv;
  sum[fv] += sum[fu];
  return 1;
}
void init(int n) {
  for (int i = 0; i <= n; ++i) f[i] = i, sum[i] = 1;
}
int main() {
  int n, m;
  int u, v;
  scanf("%d %d", &n, &m);
  init(n);
  for (int i = 0; i < m; ++i) {
    scanf("%d %d", &u, &v);
    join(u, v);
  }
  int ans = 0;
  int tmp = 0;
  for (int i = 1; i <= n; ++i) {
    ++tmp;
    if (getsum(i) == tmp) {
      tmp = 0;
    } else {
      ans += join(i, i + 1);
    }
  }
  printf("%d\n", ans);
}
