#include <bits/stdc++.h>
using namespace std;
int n, m;
namespace dsu {
int fa[200005], maxx[200005];
void init(int k) {
  for (int i = 1; i <= k; i++) fa[i] = i, maxx[i] = i;
}
int fin(int k) { return fa[k] == k ? k : (fa[k] = fin(fa[k])); }
void unite(int a, int b) {
  int x = fin(a), y = fin(b);
  if (x == y) return;
  maxx[y] = max(maxx[y], maxx[x]);
  fa[x] = y;
}
bool same(int a, int b) { return fin(a) == fin(b); }
}  // namespace dsu
using namespace dsu;
int res[200005];
int main() {
  scanf("%d %d", &n, &m);
  init(n);
  for (int i = 1, u, v; i <= m; i++) {
    scanf("%d %d", &u, &v);
    unite(u, v);
  }
  int r = 0, ans = 0;
  for (int i = 1; i <= n; i++) {
    if (i > r) {
      r = maxx[fin(i)];
    } else {
      if (!same(i, i - 1)) {
        unite(i, i - 1);
        r = maxx[fin(i)];
        ans++;
      }
    }
  }
  printf("%d\n", ans);
}
