#include <bits/stdc++.h>
using namespace std;
const int N = 1000010;
const int mod = 1000000007;
int pa[N], mn[N], mx[N];
void init() {
  for (int i = 0; i < N; i++) mx[i] = mn[i] = pa[i] = i;
}
int findset(int x) {
  if (x != pa[x]) pa[x] = findset(pa[x]);
  return pa[x];
}
void union_nodes(int a, int b) {
  int c = max(a, b);
  int d = min(a, b);
  int a1 = findset(c);
  int b1 = findset(d);
  if (a1 != b1) {
    pa[a1] = b1;
    mn[b1] = min(mn[b1], mn[a1]);
    mx[b1] = max(mx[b1], mx[a1]);
  }
}
long long a[N];
set<pair<int, int> > s;
int main() {
  ios::sync_with_stdio(false), cin.tie(0);
  int n, m, t, u, v;
  init();
  cin >> n >> m;
  for (int i = 1; i <= m; i++) {
    cin >> u >> v;
    union_nodes(u, v);
  }
  for (int i = 1; i <= n; i++) {
    if (findset(i) == i) {
      s.insert({mn[i], mx[i]});
    }
  }
  int tot = 0;
  while (s.size() != 0) {
    auto x = s.begin();
    if (s.upper_bound(*x) != s.end()) {
      auto y = s.upper_bound(*x);
      if ((*x).second > (*y).first) {
        union_nodes((*x).second, (*y).first);
        int fa = findset((*x).first);
        fa = findset(fa);
        tot++;
        s.erase(x);
        s.erase(y);
        s.insert({mn[fa], mx[fa]});
      } else
        s.erase(x);
    } else
      s.erase(x);
  }
  printf("%d\n", tot);
  return 0;
}
