#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
int f[maxn];
int find(int k) {
  if (f[k] == k) return k;
  return f[k] = find(f[k]);
}
void merge(int x, int y) {
  int a = find(x), b = find(y);
  f[b] = a;
}
struct tempp {
  long long num;
  long long g;
  long long be;
};
bool comp(tempp t1, tempp t2) {
  if (t1.num != t2.num)
    return t1.num < t2.num;
  else
    return t1.be > t2.be;
}
long long maxx[maxn], minn[maxn];
vector<tempp> seq;
long long vis[maxn];
set<long long> check;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n, m, tot = 0;
  cin >> n >> m;
  for (int i = 1; i <= n; i++) f[i] = i;
  for (int i = 1; i <= m; i++) {
    int u, v;
    cin >> u >> v;
    merge(u, v);
  }
  for (int i = 1; i <= n; i++) {
    maxx[i] = -20000000, minn[i] = 20000000;
    if (vis[find(i)] == 0) {
      tot++;
      vis[find(i)] = 1;
    }
  }
  for (int i = 1; i <= n; i++) {
    maxx[find(i)] = max(maxx[find(i)], i * 1ll);
    minn[find(i)] = min(minn[find(i)], i * 1ll);
  }
  for (int i = 1; i <= n; i++) {
    if (vis[find(i)] == 1) {
      seq.push_back({maxx[find(i)], find(i), -1});
      seq.push_back({minn[find(i)], find(i), 1});
      vis[find(i)]++;
    }
  }
  sort(seq.begin(), seq.end(), comp);
  int tott = 0;
  for (int i = 0; i < seq.size(); i++) {
    if (seq[i].be == 1) {
      if (check.size() != 0 && *check.lower_bound(0) < seq[i].num) tott++;
      check.insert(seq[i].num);
    } else
      check.erase(minn[find(seq[i].num)]);
  }
  cout << tott << endl;
  return 0;
}
