#include <bits/stdc++.h>
using namespace std;
class trio {
 public:
  long long first, second, third;
};
class DSU {
 public:
  long long *par, *size, *maxi;
  DSU(long long n) {
    par = new long long[n + 1];
    size = new long long[n + 1];
    maxi = new long long[n + 1];
    for (long long i = 0; i < n + 1; ++i) {
      par[i] = i;
      size[i] = 0;
      maxi[i] = i;
    }
  }
  long long find(long long a) {
    long long p = a, third;
    while (par[p] != p) p = par[p];
    while (p != a) {
      third = par[a];
      par[a] = p;
      a = third;
    }
    return a;
  }
  void union_(long long a, long long b) {
    long long u1 = find(a);
    long long u2 = find(b);
    if (u1 == u2) return;
    maxi[u2] = max(maxi[u2], maxi[u1]);
    maxi[u1] = max(maxi[u2], maxi[u1]);
    if (size[u1] < size[u2]) {
      par[u1] = u2;
    } else {
      if (size[u2] < size[u1]) {
        par[u2] = u1;
      } else {
        par[u1] = u2;
        size[u2]++;
      }
    }
  }
};
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  long long n, m, u, v;
  cin >> n >> m;
  DSU dsu(n);
  for (long long k = 0; k < m; ++k) {
    cin >> u >> v;
    dsu.union_(u, v);
  }
  long long ans = 0, maxi = 0, temp, i = 1, j = 1, t1, t2;
  while (i <= n) {
    temp = dsu.find(i);
    maxi = max(maxi, dsu.maxi[temp]);
    while (j <= maxi) {
      t1 = dsu.find(j);
      t2 = dsu.find(maxi);
      if (t1 != t2) {
        ans++;
        dsu.union_(t1, t2);
      }
      temp = dsu.find(j);
      maxi = max(maxi, dsu.maxi[temp]);
      j++;
    }
    i = j;
  }
  cout << ans;
  return 0;
}
