#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int g[N];
set<int> s[N];
vector<int> t[N];
vector<bool> used;
void dfs(int v, int c) {
  used[v] = true;
  g[v] = c;
  s[c].insert(v);
  for (int u : t[v]) {
    if (!used[u]) {
      dfs(u, c);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  int n, m;
  cin >> n >> m;
  for (int i = 1; i <= m; i++) {
    int x, y;
    cin >> x >> y;
    t[x].push_back(y);
    t[y].push_back(x);
  }
  used.assign(n + 1, false);
  int cnt = 0;
  for (int i = 1; i <= n; i++) {
    if (!used[i]) {
      dfs(i, cnt);
      cnt++;
    }
  }
  int res = 0;
  for (int gr = 0; gr < cnt; gr++) {
    int l = *s[gr].begin();
    int r = *--s[gr].end();
    int sz = s[gr].size();
    while (r - l + 1 != sz) {
      res++;
      gr++;
      sz += s[gr].size();
      r = max(r, *--s[gr].end());
    }
  }
  cout << res;
  return 0;
}
