#include <bits/stdc++.h>
using namespace std;
void sfsf() {
  ios::sync_with_stdio(0);
  cin.tie(nullptr);
  cout.tie(nullptr);
}
const int mxn = 4e5 + 5, N = 8e1 + 5, mod = 1e9 + 7, inf = 0x3f,
          mod2 = 999119999, mod3 = 1000992299, pow1 = 31, pow2 = 53;
int n, m, pl, par[mxn];
vector<int> vi[mxn];
bitset<mxn> vis;
int mn, mx;
vector<array<int, 2>> v;
int find_par(int node) {
  return node == par[node] ? node : par[node] = find_par(par[node]);
}
void dsu(int a, int b) { par[find_par(b)] = find_par(a); }
bool same_parent(int a, int b) { return find_par(a) == find_par(b); }
void dfs(int node) {
  vis[node] = true;
  mn = min(mn, node);
  mx = max(mx, node);
  par[node] = pl + n;
  for (auto it : vi[node])
    if (!vis[it]) dfs(it);
}
int main() {
  sfsf();
  cin >> n >> m;
  for (int i = n + 1; i <= n * 2; i++) par[i] = i;
  for (int i = 0; i < m; i++) {
    int u, vv;
    cin >> u >> vv;
    vi[u].push_back(vv);
    vi[vv].push_back(u);
  }
  for (int i = 1; i <= n; i++) {
    if (!vis[i]) {
      ++pl;
      mn = n + 1;
      mx = 0;
      dfs(i);
      v.push_back({mn, mx});
    }
  }
  int ans = 0;
  sort(v.begin(), v.end());
  int siz = v.size();
  int curr = 1;
  for (int i = 0; i < siz; i++) {
    if (v[i][0] > curr) curr = v[i][0];
    if (v[i][0] == v[i][1]) continue;
    for (; curr <= v[i][1]; curr++) {
      if (!same_parent(curr, v[i][0])) {
        dsu(curr, v[i][0]);
        ans++;
      }
    }
  }
  cout << ans;
  return 0;
}
