#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 19;
int t, n, m;
int fa[N];
int fd_ys(int kid) {
  if (fa[kid] != kid) fa[kid] = fd_ys(fa[kid]);
  return fa[kid];
}
void init() {
  for (int i = 1; i <= n; ++i) fa[i] = i;
}
int main() {
  scanf("%d %d", &n, &m);
  init();
  while (m--) {
    int u, v;
    scanf("%d %d", &u, &v);
    u = fd_ys(u);
    v = fd_ys(v);
    if (u == v) continue;
    if (u < v) swap(u, v);
    fa[u] = v;
  }
  int now = n, ans = 0;
  for (int i = n; i > 0; --i) {
    int father = fd_ys(i);
    now = min(now, father);
    if (father != now) {
      ans++;
      fa[father] = now;
    }
  }
  printf("%d\n", ans);
  return 0;
}
