#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9;
const long long INF = 1e18;
const int md = 1e9 + 7;
const int N = 2e5 + 1;
vector<int> g[N];
int p[N], s[N], mx[N], mn[N];
bool did[N];
void make(int v) { p[v] = v, s[v] = 1, mx[v] = v, mn[v] = v; }
int fin(int v) {
  if (p[v] == v) return v;
  return p[v] = fin(p[v]);
}
void un(int a, int b) {
  a = fin(a);
  b = fin(b);
  if (a == b) return;
  if (s[a] < s[b]) swap(a, b);
  s[a] += s[b], mx[a] = max(mx[a], mx[b]);
  p[b] = a;
  mn[a] = min(mn[a], mn[b]);
}
signed main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int n, m;
  cin >> n >> m;
  for (int f = 0; f < n; ++f) make(f);
  for (int j = 0; j < m; ++j) {
    int u, v;
    cin >> u >> v;
    --u, --v;
    un(u, v);
  }
  int curr = 0;
  int ans = 0;
  int may;
  bool isn = 0;
  while (curr < n) {
    if (mx[fin(curr)] - mn[fin(curr)] + 1 == s[fin(curr)]) {
      int lead = fin(curr);
      while (curr < n && fin(curr) == lead) {
        curr++;
      }
      isn = 1;
    } else {
      int lead = fin(curr);
      if (isn) may = curr;
      isn = 0;
      while (may < n && fin(may) == lead) {
        may++;
      }
      un(may, curr);
      ans++;
    }
  }
  cout << ans;
  return 0;
}
