#include <bits/stdc++.h>
using namespace std;
struct s {
  int l = -1, r = -1, c = 0;
};
int modex(int x, int n) {
  if (!n) return 1;
  if (n & 1)
    return (x * modex((x * x) % 1000000007, (n - 1) / 2)) % 1000000007;
  else
    return modex((x * x) % 1000000007, n / 2);
}
int modinv(int n) { return modex(n, 1000000007 - 2); }
vector<int> adj[200005];
int n, m, u, v, max_so_far = -1;
bool vis[200005];
void dfs(int src) {
  vis[src] = true;
  for (auto it : adj[src]) {
    if (!vis[it]) {
      max_so_far = max(max_so_far, it);
      dfs(it);
    }
  }
}
void solve() {
  cin >> n >> m;
  memset(vis, 0, sizeof(vis));
  for (int i = 0; i < m; i++) {
    cin >> u >> v;
    adj[u - 1].push_back(v - 1);
    adj[v - 1].push_back(u - 1);
  }
  int ans = 0;
  for (int i = 0; i < n; i++) {
    if (!vis[i]) {
      if (i < max_so_far) ans++;
      dfs(i);
    }
  }
  cout << ans << "\n";
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t = 1;
  while (t--) {
    solve();
  }
  return 0;
}
