#include <bits/stdc++.h>
using namespace std;
vector<long long> edge[200020];
vector<long long> cp[200020];
long long vis[200020];
long long clr[200020];
void dfs(long long x, long long c) {
  vis[x] = 1;
  clr[x] = c;
  cp[c].emplace_back(x);
  for (long long i : edge[x]) {
    if (!vis[i]) dfs(i, c);
  }
}
long long lead[200020];
void init(long long n = 200020) {
  for (long long i = 0; i <= n; i++) lead[i] = i;
}
long long find(long long x) {
  if (lead[x] == x)
    return x;
  else
    return lead[x] = find(lead[x]);
}
void U(long long x, long long y) {
  x = find(x);
  y = find(y);
  lead[x] = y;
}
bool same(long long x, long long y) { return find(x) == find(y); }
signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  long long n, m;
  cin >> n >> m;
  for (long long i = 0, u, v; i < m; i++) {
    cin >> u >> v;
    edge[u].emplace_back(v);
    edge[v].emplace_back(u);
  }
  long long cnum = 0;
  for (long long i = 1; i <= n; i++) {
    long long mi = INT_MAX, ma = INT_MIN;
    if (!vis[i]) dfs(i, ++cnum);
  }
  memset(vis, 0, sizeof(vis));
  for (long long i = 1; i <= cnum; i++) sort(cp[i].begin(), cp[i].end());
  init();
  set<long long> uns;
  for (long long i = 1; i <= n; i++) uns.emplace(i);
  long long ans = 0;
  for (long long i = 1; i <= cnum; i++) {
    for (long long j = cp[i][0]; j <= cp[i].back();) {
      if (!same(i, clr[j])) {
        ans++;
        U(i, clr[j]);
      }
      uns.erase(j);
      auto iter = uns.upper_bound(j);
      if (iter != uns.end())
        j = *iter;
      else
        j = INT_MAX;
    }
  }
  cout << ans << endl;
  return 0;
}
