#include <bits/stdc++.h>
using namespace std;
int Arr[200005], sz[200005], maxi[200005];
int root(int i) {
  while (Arr[i] != i) {
    i = Arr[i];
  }
  return i;
}
bool find(int A, int B) {
  if (root(A) == root(B))
    return true;
  else
    return false;
}
void initialize(int N) {
  for (int i = 1; i <= N; i++) {
    Arr[i] = i;
    sz[i] = 1;
    maxi[i] = i;
  }
}
int weightedunion(int A, int B) {
  int root_A = root(A);
  int root_B = root(B);
  if (root_A == root_B) {
    return maxi[root_A];
  }
  if (sz[root_A] < sz[root_B]) {
    Arr[root_A] = Arr[root_B];
    sz[root_B] += sz[root_A];
    maxi[root_B] = max(maxi[root_B], maxi[root_A]);
    return maxi[root_B];
  } else {
    Arr[root_B] = Arr[root_A];
    sz[root_A] += sz[root_B];
    maxi[root_A] = max(maxi[root_B], maxi[root_A]);
    return maxi[root_A];
  }
}
int x[200005], y[200005];
int main() {
  int n, m, i;
  scanf("%d %d", &n, &m);
  ;
  initialize(n);
  for (i = 0; i < m; i++) {
    scanf("%d %d", &x[i], &y[i]);
    ;
    weightedunion(x[i], y[i]);
  }
  i = 1;
  int ans = 0, j, maax;
  while (i <= n) {
    j = i;
    maax = maxi[root(i)];
    while (j <= maax) {
      if (!find(i, j)) {
        ans++;
        maax = weightedunion(i, j);
      }
      j++;
    }
    i = j;
  }
  printf("%d", ans);
  ;
}
