#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
const double PI = 3.141592653589793238463;
const int N = 2e5 + 10;
vector<pair<int, int>> bad;
vector<int> new_road;
int parent[N];
int root[N];
int mx[N];
bool visited[N];
int find(int x) {
  if (parent[x] == x) return x;
  return find(parent[x]);
}
void merge(int x, int y) {
  int parentx = find(x);
  int parenty = find(y);
  if (parentx == parenty) return;
  if (parentx < parenty) {
    root[parentx] += root[parenty];
    parent[parenty] = parentx;
    mx[parentx] = max({mx[parentx], x, y, mx[parenty]});
  } else {
    root[parenty] += root[parentx];
    parent[parentx] = parenty;
    mx[parenty] = max({mx[parentx], x, y, mx[parenty]});
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  int x, y;
  cin >> x >> y;
  for (int i = 1; i <= x; i++) {
    parent[i] = i;
    root[i] = 1;
  }
  int r, l;
  pair<int, int> p[y];
  for (int i = 0; i < y; i++) cin >> p[i].first >> p[i].second;
  sort(p, p + y);
  for (int i = 0; i < y; i++) {
    merge(p[i].first, p[i].second);
  }
  int temp, ans = 0, beg = 0;
  for (int i = 1; i <= x; i++) {
    temp = find(i);
    if (temp < beg) continue;
    if (temp != beg) {
      if (i <= mx[beg]) {
        ans++;
        merge(temp, beg);
      } else
        beg = temp;
    }
  }
  cout << ans << '\n';
  return 0;
}
