#include <bits/stdc++.h>
using namespace std;
struct Debug {
  int cnt = 0;
  bool on = false;
  char debug[10] = "debug";
  template <class T>
  Debug& operator<<(const T& v) {
    if (on && cnt++ == 0) cerr << "debug: ";
    if (on) cerr << v << ' ';
    return *this;
  }
  Debug& operator<<(ostream& (*pManip)(ostream&)) {
    if (on) cerr << (*pManip);
    cnt = 0;
    return *this;
  }
} debug;
const int MAXN = 2e5 + 10;
int root[MAXN], size[MAXN], max_e[MAXN];
void init() {
  for (int i = 0; i < MAXN; i++) {
    root[i] = i;
    size[i] = 1;
    max_e[i] = i;
  }
}
int find(int i) {
  if (root[i] != i)
    return root[i] = find(root[i]);
  else
    return i;
}
int same(int i, int j) { return find(i) == find(j); }
void join(int i, int j) {
  if (same(i, j)) return;
  int ri = find(i);
  int rj = find(j);
  if (size[ri] >= size[rj]) {
    root[rj] = ri;
    size[ri] += size[rj];
    max_e[ri] = max(max_e[ri], max_e[rj]);
  } else {
    root[ri] = rj;
    size[rj] += size[ri];
    max_e[rj] = max(max_e[ri], max_e[rj]);
  }
}
int get_max(int i) { return max_e[find(i)]; }
int n, m;
int main(int argc, char* argv[]) {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  if (argc > 1 && !strcmp(argv[1], debug.debug)) debug.on = true;
  init();
  cin >> n >> m;
  int u, v;
  for (int i = 0; i < m; i++) {
    cin >> u >> v;
    join(u, v);
  }
  int cur_min = 1, cur_max;
  int res = 0;
  while (cur_min <= n) {
    cur_max = get_max(cur_min);
    for (int i = cur_min; i <= cur_max; i++) {
      if (find(i) != find(cur_min)) {
        res++;
        join(i, cur_min);
        cur_max = get_max(i);
      }
    }
    cur_min = cur_max + 1;
  }
  cout << res << endl;
  return 0;
}
