#include <bits/stdc++.h>
using namespace std;
const int N = int(2e5) + 10;
vector<int> adj[N];
bool visited[N], done[N];
int c[N];
int cnt = 0;
map<int, int> fst, lst;
void dfs(int s) {
  if (visited[s]) return;
  visited[s] = true;
  c[s] = cnt;
  for (auto v : adj[s]) {
    dfs(v);
  }
}
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int u, v;
    cin >> u >> v;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  for (int i = 1; i <= n; i++) {
    if (!visited[i]) {
      cnt++;
      dfs(i);
    }
  }
  for (int i = 1; i <= n; i++) {
    if (fst[c[i]] > 0)
      lst[c[i]] = i;
    else {
      fst[c[i]] = lst[c[i]] = i;
    }
  }
  int ans = 0, i = 1;
  while (i <= n) {
    int currMax = lst[c[i]];
    done[c[i]] = true;
    while (i <= n && i <= currMax) {
      if (!done[c[i]]) {
        ans++;
        done[c[i]] = true;
        currMax = max(currMax, lst[c[i]]);
      }
      i++;
    }
  }
  cout << ans << endl;
  return 0;
}
