#include <bits/stdc++.h>
using namespace std;
long long int n, m;
vector<long long int> a[200005];
long long int rankof[200005];
long long int parentof[200005];
long long int maxof[200005];
void initialize() {
  for (long long int i = 0; i <= 200005; i++) {
    rankof[i] = 1;
    parentof[i] = i;
    maxof[i] = i;
  }
}
long long int root(long long int x) {
  if (x == parentof[x]) {
    return x;
  }
  parentof[x] = root(parentof[x]);
  return parentof[x];
}
void combine(long long int x, long long int y) {
  x = root(x);
  y = root(y);
  long long int maxx = max(maxof[x], maxof[y]);
  if (x != y) {
    if (rankof[x] >= rankof[y]) {
      parentof[y] = x;
      rankof[x] += rankof[y];
      maxof[x] = maxx;
    } else {
      parentof[x] = y;
      rankof[y] += rankof[x];
      maxof[y] = maxx;
    }
  }
  return;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long int i, j;
  cin >> n >> m;
  initialize();
  for (i = 0; i < m; i++) {
    long long int u, v;
    cin >> u >> v;
    combine(u, v);
  }
  long long int curmax, cnt = 0;
  for (i = 1; i <= n;) {
    curmax = maxof[root(i)];
    j = i + 1;
    while (j <= curmax) {
      if (root(j) != root(i)) {
        combine(i, j);
        cnt++;
      }
      curmax = maxof[root(i)];
      j++;
    }
    i = j;
  }
  cout << cnt;
  return 0;
}
