#include <bits/stdc++.h>
using namespace std;
long long n, m, mi = INT_MAX, ma = 0, cnt = 0;
vector<int> adj[400005];
bool vis[400005];
long long max(long long a, long long b) { return (a > b) ? a : b; }
long long min(long long a, long long b) { return (a > b) ? b : a; }
void bfs(int s) {
  vis[s] = 1;
  cnt++;
  ma = max(ma, s);
  mi = min(mi, s);
  for (auto i : adj[s])
    if (!vis[i]) bfs(i);
}
void solve() {
  vector<std::pair<int, int> > p;
  for (long long i = 0; i < (n); ++i) {
    if (!vis[i + 1]) {
      mi = INT_MAX;
      ma = 0;
      mi;
      bfs(i + 1);
      p.push_back({mi, ma});
    }
  }
  sort(p.begin(), p.end());
  int e = -1, ans = 0;
  for (auto i : p) {
    if (i.first <= e) ans++;
    e = max(e, i.second);
  }
  cout << ans;
}
int main() {
  std::ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long test = 1;
  while (test--) {
    cin >> n >> m;
    long long u, v;
    for (long long i = 0; i < (m); ++i) {
      cin >> u >> v;
      adj[u].push_back(v);
      adj[v].push_back(u);
    }
    solve();
  }
}
