#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
const int inf = 0x7fffffff / 2;
int n, m;
int fa[maxn];
int vis[maxn];
struct edge {
  int u;
  int v;
  int w;
} e[maxn];
struct ex {
  int mi;
  int mx;
  int sum;
} ex[maxn];
int father(int x) {
  if (x != fa[x]) fa[x] = father(fa[x]);
  return fa[x];
}
void join(int x, int y) {
  ex[father(y)].mi = min(ex[father(y)].mi, ex[father(x)].mi);
  ex[father(y)].mx = max(ex[father(y)].mx, ex[father(x)].mx);
  ex[father(y)].sum += ex[father(x)].sum;
  fa[father(x)] = father(y);
}
int judge_node(int x) {
  x = father(x);
  int mi = ex[x].mi;
  int mx = ex[x].mx;
  int sum = ex[x].sum;
  if (mi == -inf) return 1;
  mi = ((mi - 1) * mi) / 2;
  mx = ((mx + 1) * mx) / 2;
  if ((mx - mi) != sum)
    return 1;
  else
    return 0;
}
void init(int u, int v) {
  ex[u].sum = u;
  ex[v].sum = v;
  ex[u].mx = u;
  ex[u].mi = u;
  ex[v].mx = v;
  ex[v].mi = v;
}
int main() {
  ios::sync_with_stdio(false);
  cin >> n >> m;
  for (int i = 1; i <= n; i++) {
    fa[i] = i;
    ex[i].mi = inf;
    ex[i].mx = -inf;
    ex[i].sum = 0;
  }
  for (int i = 1; i <= m; i++) {
    cin >> e[i].u >> e[i].v;
    init(e[i].u, e[i].v);
  }
  for (int i = 1; i <= m; i++) {
    if (father(e[i].u) != father(e[i].v)) {
      join(e[i].u, e[i].v);
    }
  }
  int ans = 0;
  int mxx = -inf, last;
  for (int i = 1; i <= n; i++) {
    if (judge_node(i) && vis[father(i)] == 0) {
      int l = ex[father(i)].mi;
      int r = ex[father(i)].mx;
      for (int j = l; j < r; j++) {
        if (father(j) != father(i)) {
          join(i, j);
          ans++;
          last = j;
        }
        l = ex[father(i)].mi;
        r = ex[father(i)].mx;
      }
      vis[father(last)] = 1;
    }
  }
  cout << ans << endl;
  return 0;
}
