#include <bits/stdc++.h>
using namespace std;
int weight[200005], root[200005];
int findroot(int x) {
  while (root[x] != x) {
    root[x] = root[root[x]];
    x = root[x];
  }
  return x;
}
void merge(int x, int y) {
  x = findroot(x);
  y = findroot(y);
  if (x == y) return;
  if (weight[x] > weight[y]) {
    root[y] = x;
    weight[x] += weight[y];
  } else {
    root[x] = y;
    weight[y] += weight[x];
  }
}
int op[200005], opx[200005];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  int n, m;
  cin >> n >> m;
  for (int i = 1; i < n + 1; i++) {
    weight[i] = 1;
    root[i] = i;
  }
  for (int i = 1; i < m + 1; i++) {
    int x, y;
    cin >> x >> y;
    merge(x, y);
  }
  for (int i = 1; i < n + 1; i++) {
    int x = findroot(i);
    op[x] = min(i, op[x]);
    opx[x] = max(i, opx[x]);
  }
  int mn = 1, mxn = 1;
  int cnt = 0;
  for (int i = 1; i < n + 1; i++) {
    if (i > mxn) {
      mn = i;
      mxn = i;
    }
    int x = findroot(mxn);
    int y = findroot(i);
    if (x != y) {
      cnt++;
      merge(x, y);
      op[x] = op[y] = min(op[x], op[y]);
      opx[x] = opx[y] = max(opx[x], opx[y]);
    }
    mxn = opx[x];
  }
  cout << cnt;
}
