#include <bits/stdc++.h>
const int MXN = 2e5 + 100;
const long long MNN = 5e3 + 100;
const long long MOD = 1e9 + 7;
const long long INF = 1e18;
const long long OO = 1e9 + 500;
using namespace std;
int n, m, p[MXN], ans;
pair<int, int> lmt[MXN];
int fd(int x) {
  if (p[x] == x)
    return x;
  else
    return p[x] = fd(p[x]);
}
int main() {
  srand(time(0));
  int n;
  cin >> n >> m;
  for (int i = 1; i <= n; i++) {
    p[i] = i;
    lmt[i] = {i, i};
  }
  for (int i = 1; i <= m; i++) {
    int u, v;
    cin >> u >> v;
    int left = fd(u);
    int right = fd(v);
    if (left != right) {
      if (rand() % 2 == 1) {
        p[left] = right;
        p[u] = right;
        lmt[right].first = min(lmt[right].first, lmt[left].first);
        lmt[right].second = max(lmt[right].second, lmt[left].second);
      } else {
        p[right] = left;
        p[v] = left;
        lmt[left].first = min(lmt[left].first, lmt[right].first);
        lmt[left].second = max(lmt[left].second, lmt[right].second);
      }
    } else {
      p[u] = left;
      p[v] = left;
    }
  }
  int cur = 1;
  while (cur <= n) {
    int batya = fd(cur);
    for (int i = lmt[batya].first; i <= lmt[batya].second; i++) {
      int parent = fd(i);
      if (parent != batya) {
        ans++;
        p[parent] = batya;
        p[i] = batya;
        lmt[batya].second = max(lmt[parent].second, lmt[batya].second);
      } else {
        p[i] = batya;
      }
    }
    cur = lmt[batya].second + 1;
  }
  cout << ans;
  return 0;
}
