#include <bits/stdc++.h>
using namespace std;
const long long LINF = 2e18;
const long long MOD = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const int MAXN = 200050;
int fa[MAXN];
int find(int x) { return x == fa[x] ? x : (fa[x] = find(fa[x])); }
void merge(int x, int y) {
  int fax = find(x), fay = find(y);
  if (fax > fay) swap(fax, fay);
  fa[fay] = fax;
}
int fst[MAXN], lst[MAXN];
void solve(int t) {
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) {
    fa[i] = i;
    fst[i] = INF;
    lst[i] = 0;
  }
  int u, v;
  for (int i = 1; i <= m; i++) {
    scanf("%d%d", &u, &v);
    merge(u, v);
  }
  for (int i = 1; i <= n; i++) {
    find(i);
  }
  for (int i = 1; i <= n; i++) {
    fst[fa[i]] = min(fst[fa[i]], i);
    lst[fa[i]] = max(lst[fa[i]], i);
  }
  int fax;
  int ans = 0;
  for (int i = 1; i <= n; i++) {
    if (fa[i] != i) continue;
    for (int j = fst[i]; j <= lst[i]; j++) {
      fax = find(j);
      if (fax != fa[i]) {
        ans++;
        fa[fax] = fa[i];
        lst[i] = max(lst[i], lst[fax]);
        fst[i] = max(fst[i], fst[fax]);
      }
    }
  }
  printf("%d\n", ans);
}
signed main() {
  int t = 1;
  for (int i = 1; i <= t; i++) {
    solve(i);
  }
}
