#include <bits/stdc++.h>
using namespace std;
vector<int> G[200005];
int mx = 1, vis[200005];
void dfs(int u) {
  mx = max(mx, u);
  vis[u] = 1;
  for (int i = 0; i < G[u].size(); i++) {
    if (!vis[G[u][i]]) {
      dfs(G[u][i]);
    }
  }
}
int main() {
  int n, m, ans = 0;
  scanf("%d%d", &n, &m);
  while (m--) {
    int u, v;
    scanf("%d%d", &u, &v);
    G[u].push_back(v);
    G[v].push_back(u);
  }
  for (int i = 1; i <= n; i++) {
    if (!vis[i]) {
      if (i < mx) ans++;
      dfs(i);
    }
  }
  printf("%d", ans);
  return 0;
}
