#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
ll mod = 1e9 + 7;
vector<int> arr, s;
int parent(int a) {
  while (arr[a] != a) {
    arr[a] = arr[arr[a]];
    a = arr[a];
  }
  return a;
}
void find_union(int a, int b) {
  int parent_a = parent(a);
  int parent_b = parent(b);
  if (s[parent_a] > s[parent_b]) {
    arr[parent_b] = parent_a;
    s[parent_a] += s[parent_b];
  } else {
    arr[parent_a] = parent_b;
    s[parent_b] += s[parent_a];
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int n, m;
  cin >> n >> m;
  arr.assign(n + 1, 0);
  s.assign(n + 1, 1);
  vector<int> graph[n + 1];
  for (int i = 1; i <= n; i++) {
    arr[i] = i;
  }
  vector<pair<int, int>> comp(n + 1);
  for (int i = 1; i <= n; i++) {
    comp[i] = {i, i};
  }
  for (int i = 0; i < m; i++) {
    int a, b;
    cin >> a >> b;
    int parent_a = parent(a);
    int parent_b = parent(b);
    if (parent_a != parent_b) {
      int l1 = comp[parent_a].first;
      int l2 = comp[parent_b].first;
      int r1 = comp[parent_a].second;
      int r2 = comp[parent_b].second;
      int l = min(l1, l2);
      int r = max(r1, r2);
      find_union(a, b);
      comp[parent(a)] = {l, r};
    }
  }
  int count = 0;
  for (int i = 1; i <= n; i++) {
    if (parent(i) >= i) {
      int l = comp[parent(i)].first;
      int r = comp[parent(i)].second;
      for (int j = l; j <= r; j++) {
        if (parent(j) != parent(i)) {
          count++;
          r = max(r, comp[parent(j)].second);
          find_union(i, j);
        }
      }
      i = r;
    }
  }
  cout << count;
}
