#include <bits/stdc++.h>
using namespace std;
vector<bool> visited;
vector<list<int> > child;
pair<int, int> now({1, 1});
void dfs(int node) {
  now.first = min(now.first, node);
  now.second = max(now.second, node);
  visited[node] = true;
  for (int i : child[node]) {
    if (!visited[i]) dfs(i);
  }
}
int main() {
  int n, m;
  cin >> n >> m;
  visited.resize(n + 1, false);
  child.resize(n + 1, list<int>());
  int ans = 0;
  int l, k;
  for (int i = 0; i < m; i++) {
    cin >> l >> k;
    child[l].push_back(k);
    child[k].push_back(l);
  }
  pair<int, int> last({0, 0});
  for (int i = 0; i < n; i++) {
    if (!visited[i + 1]) {
      now = make_pair(i + 1, i + 1);
      dfs(i + 1);
      if (now.first <= last.second) {
        last.second = max(last.second, now.second);
        ans++;
      } else
        last = now;
    }
  }
  cout << ans;
}
