#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 11;
int f[maxn];
int findf(int x) {
  if (f[x] == x)
    return x;
  else
    return f[x] = findf(f[x]);
}
void unit(int x, int y) {
  int x1 = findf(x), y1 = findf(y);
  if (x1 == y1) return;
  f[min(x1, y1)] = max(x1, y1);
}
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 1; i <= n; i++) f[i] = i;
  for (int i = 1; i <= m; i++) {
    int a, b;
    cin >> a >> b;
    unit(a, b);
  }
  int ans = 0;
  for (int i = 1; i <= n; i++) {
    if (findf(i) == i) continue;
    for (int j = i + 1; j <= findf(i); j++) {
      int b = findf(j);
      if (b != findf(i)) {
        unit(findf(i), b);
        ans++;
      }
    }
    i = findf(i);
  }
  cout << ans << endl;
}
