#include <bits/stdc++.h>
using namespace std;
vector<vector<long long>> adj;
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long n, m;
  cin >> n >> m;
  adj.resize(n);
  for (long long i = 0; i < m; i++) {
    long long u, v;
    cin >> u >> v;
    --u, --v;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  vector<array<long long, 2>> ranges;
  vector<bool> visited(n, false);
  for (long long i = 0; i < n; i++) {
    if (visited[i]) continue;
    long long range_min = i, range_max = i;
    queue<long long> q;
    q.push(i);
    visited[i] = true;
    while (q.size()) {
      long long u = q.front();
      q.pop();
      for (long long v : adj[u]) {
        if (!visited[v]) {
          visited[v] = true;
          q.push(v);
          if (v < range_min) range_min = v;
          if (v > range_max) range_max = v;
        }
      }
    }
    ranges.push_back({range_min, range_max});
  }
  vector<vector<long long>> adj_comp(ranges.size());
  long long max_vtx = 0;
  for (long long i = 1; i < ranges.size(); i++) {
    if (ranges[i][0] > ranges[max_vtx][1]) {
      max_vtx = i;
    } else {
      adj_comp[i].push_back(max_vtx);
      adj_comp[max_vtx].push_back(i);
      if (ranges[i][1] > ranges[max_vtx][1]) {
        max_vtx = i;
      }
    }
  }
  long long res = 0;
  vector<bool> visited_comp(ranges.size(), false);
  for (long long i = 0; i < (long long)ranges.size(); i++) {
    long long this_size = 0;
    if (visited_comp[i]) continue;
    queue<long long> q;
    q.push(i);
    this_size++;
    visited_comp[i] = true;
    while (q.size()) {
      long long u = q.front();
      q.pop();
      for (long long v : adj_comp[u]) {
        if (!visited_comp[v]) {
          this_size++;
          visited_comp[v] = true;
          q.push(v);
        }
      }
    }
    res += this_size - 1;
  }
  cout << res << "\n";
  return 0;
}
