#include <bits/stdc++.h>
const int MAX_N = 2e5 + 5;
int n, m, dsu[MAX_N], ans;
int root(int x) {
  if (dsu[x] < 0)
    return x;
  else
    return dsu[x] = root(dsu[x]);
}
void connect(int x, int y) {
  x = root(x);
  y = root(y);
  if (x == y) return;
  if (x < y) std::swap(x, y);
  dsu[x] += dsu[y];
  dsu[y] = x;
}
int main() {
  memset(dsu, 0xff, sizeof(dsu));
  scanf("%d%d", &n, &m);
  for (int i = 0; i < m; ++i) {
    int u, v;
    scanf("%d%d", &u, &v);
    connect(u, v);
  }
  for (int i = 1; i <= n;) {
    int p = root(i);
    for (int j = i + 1; j <= p; ++j)
      if (root(i) != root(j)) {
        ++ans;
        connect(i, j);
        p = std::max(p, root(i));
      }
    i = p + 1;
  }
  printf("%d\n", ans);
}
