#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 7;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
int n, m, fa[maxn];
int Find(int x) {
  if (fa[x] == x)
    return x;
  else
    return fa[x] = Find(fa[x]);
}
int main() {
  scanf("%d %d", &n, &m);
  for (int i = 0; i <= n; i++) fa[i] = i;
  for (int i = 0; i < m; i++) {
    int x, y;
    scanf("%d %d", &x, &y);
    int fx = Find(x);
    int fy = Find(y);
    if (fx > fy) swap(fx, fy);
    fa[fx] = fy;
  }
  int ans = 0;
  for (int i = 1; i <= n;) {
    int h = Find(i);
    while (++i <= h) {
      int hh = Find(i);
      if (hh != h) {
        if (hh > h) swap(hh, h);
        fa[hh] = h;
        ans++;
      }
    }
  }
  printf("%d\n", ans);
  return 0;
}
