#include <bits/stdc++.h>
using namespace std;
const int nax = 2e5 + 5;
vector<int> adj[nax];
bool v[nax];
int mn;
int mx;
int ans;
int cnt;
vector<pair<int, int>> components;
void dfs(int s) {
  v[s] = true;
  for (auto u : adj[s]) {
    if (!v[u]) {
      cnt++;
      mn = min(mn, u);
      mx = max(mx, u);
      dfs(u);
    }
  }
}
void total() {
  if (mx - mn > cnt) {
    ans++;
  }
  mx = 0;
  mn = 0;
  cnt = 0;
}
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 1; i <= m; i++) {
    int a, b;
    cin >> a >> b;
    adj[a].push_back(b);
    adj[b].push_back(a);
  }
  for (int i = 1; i <= n; i++) {
    if (!v[i]) {
      mn = i;
      mx = i;
      dfs(i);
      components.push_back({mn, mx});
    }
  }
  int ans = 0;
  int endpt = -1;
  for (auto comp : components) {
    if (comp.first <= endpt) {
      ans++;
    }
    endpt = max(endpt, comp.second);
  }
  cout << ans << endl;
  return 0;
}
