#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> G[200005];
int par[200005];
vector<int> comp[200005];
int size[200005];
int mn[200005], mx[200005];
void unionF(int u, int v) {
  if (par[u] == par[v]) {
    return;
  }
  int x = par[u], y = par[v];
  if (size[x] < size[y]) swap(x, y);
  size[x] += size[y];
  for (int z : comp[y]) {
    comp[x].push_back(z);
    mn[x] = min(mn[x], z);
    mx[x] = max(mx[x], z);
    par[z] = x;
  }
  size[y] = 0;
  comp[y].clear();
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++)
    par[i] = i, size[i] = 1, comp[i].push_back(i), mn[i] = i, mx[i] = i;
  for (int i = 0; i < m; i++) {
    int x, y;
    scanf("%d%d", &x, &y);
    G[x].push_back(y);
    G[y].push_back(x);
    unionF(x, y);
  }
  set<int> all_nodes;
  for (int i = 1; i <= n; i++) all_nodes.insert(i);
  int ans = 0;
  for (int i = 1; i <= n; i++) {
    if (size[i] == 1) continue;
    int x = par[i];
    int from = mn[x], to = mx[x];
    while (true) {
      auto it = all_nodes.lower_bound(from);
      if (it == all_nodes.end() || *it > to) break;
      if (par[i] != par[*it]) {
        unionF(x, *it);
        ans++;
      }
      all_nodes.erase(it);
    }
  }
  printf("%d\n", ans);
  return 0;
}
