#include <bits/stdc++.h>
using namespace std;
int n, m;
int a[220000], b[220000];
int g[220000];
int fa[220000];
int f(int t) {
  if (fa[t] != t) fa[t] = f(fa[t]);
  return fa[t];
}
int sol() {
  int ans = 0;
  int cur = 1;
  for (int i = 1; i <= n; ++i) {
    if (g[i] == 0) continue;
    cur = max(cur, i);
    int max_t = g[i];
    if (max_t < cur) continue;
    for (int j = cur + 1; j <= max_t; ++j) {
      if (f(j - 1) != f(j)) {
        fa[f(j - 1)] = f(j);
        ++ans;
      }
    }
    cur = max_t;
  }
  return ans;
}
int main() {
  cin >> n >> m;
  for (int i = 1; i < n + 1; ++i) fa[i] = i;
  for (int i = 0; i < m; ++i) {
    int a, b;
    scanf("%d%d", &a, &b);
    fa[f(a)] = f(b);
    g[a] = max(g[a], b);
    g[b] = max(g[b], a);
  }
  cout << sol() << endl;
}
