#include <bits/stdc++.h>
using namespace std;
const int MAXN = 200010;
int n, m;
int mx[MAXN];
int mn[MAXN];
int pai[MAXN];
int peso[MAXN];
bool marc[MAXN];
int find(int i) {
  if (pai[i] == i) return i;
  return pai[i] = find(pai[i]);
}
void join(int i, int j) {
  i = find(i);
  j = find(j);
  if (i == j) return;
  if (peso[i] < peso[j]) swap(i, j);
  pai[j] = i;
  if (peso[i] == peso[j]) peso[i]++;
  mx[i] = max(mx[i], mx[j]);
  mn[i] = min(mn[i], mn[j]);
}
int main() {
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= n; i++) pai[i] = mn[i] = mx[i] = i;
  for (int i = 1; i <= m; i++) {
    int U, V;
    scanf("%d %d", &U, &V);
    join(U, V);
  }
  int ans = 0;
  for (int i = 1; i <= n; i++) {
    if (marc[i]) continue;
    marc[i] = true;
    for (int j = mn[find(i)]; j < mx[find(i)]; j++) {
      marc[j] = true;
      if (find(j) != find(j + 1)) {
        join(j, j + 1);
        ans++;
      }
    }
    marc[mx[find(i)]] = true;
  }
  printf("%d\n", ans);
}
