#include <bits/stdc++.h>
using namespace std;
const int N = 200005;
long long int p[N], r[N], mx[N];
void make_set() {
  for (int i = 0; i < N; i++) {
    p[i] = i;
    mx[i] = i;
  }
}
long long int find_set(int x) {
  if (p[x] == x) return x;
  p[x] = find_set(p[x]);
  return p[x];
}
void Union(long long int u, long long int v) {
  long long int x = find_set(u);
  long long int y = find_set(v);
  if (r[x] > r[y]) {
    p[y] = x;
    mx[x] = max(mx[x], mx[y]);
  } else if (r[x] < r[y]) {
    p[x] = y;
    mx[y] = max(mx[x], mx[y]);
  } else {
    p[x] = y;
    r[y]++;
    mx[y] = max(mx[x], mx[y]);
  }
}
int a[200005];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t = 1;
  while (t--) {
    make_set();
    long long int n, m;
    cin >> n >> m;
    for (int i = 0; i < m; i++) {
      long long int u, v;
      cin >> u >> v;
      Union(u, v);
    }
    int ans = 0;
    for (int i = 1; i < n; i++) {
      if (mx[find_set(i)] > i + 1) {
        if (find_set(i) != find_set(i + 1)) {
          Union(i, i + 1);
          ans++;
        }
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
