#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
struct UF {
  int pa, r;
} uf[N];
int find(int x) {
  if (x == uf[x].pa) return x;
  return uf[x].pa = find(uf[x].pa);
}
void U(int x, int y) {
  x = find(x), y = find(y);
  if (x > y) swap(x, y);
  uf[x].r = max(uf[x].r, uf[y].r);
  uf[y].pa = x;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n, m, i, x, y;
  cin >> n >> m;
  for (i = 1; i <= n; ++i) uf[i].pa = i, uf[i].r = i;
  for (i = 1; i <= m; ++i) {
    cin >> x >> y;
    U(x, y);
  }
  int r = 0, rt = 0, ans = 0;
  for (i = 1; i <= n; ++i) {
    if (i <= r) {
      if (find(i) != rt) {
        ++ans;
        U(i, rt);
        r = max(r, uf[find(i)].r);
      }
    } else {
      r = uf[i].r;
      rt = find(i);
    }
  }
  cout << ans << endl;
  return 0;
}
