#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long int llINF = 0x3f3f3f3f3f3f3f;
const int N = 1e6 + 1;
int pai[N], peso[N], grt[N];
int n, vis[N], m;
vector<int> adj[N];
int find(int x) { return (pai[x] == x) ? x : (pai[x] = find(pai[x])); }
void join(int x, int y) {
  if ((x = find(x)) == (y = find(y))) return;
  if (peso[x] > peso[y]) swap(x, y);
  pai[x] = y;
  if (peso[x] == peso[y]) peso[y]++;
  grt[y] = max(grt[y], grt[x]);
}
void dfs(int r) {
  vis[r] = 1;
  for (auto x : adj[r]) {
    if (vis[x]) continue;
    join(r, x);
  }
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) {
    pai[i] = grt[i] = i;
    peso[i] = 1;
  }
  for (int i = 0; i < m; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    adj[a].push_back(b);
    adj[b].push_back(a);
  }
  for (int i = 1; i <= n; i++) {
    if (!vis[i]) dfs(i);
  }
  int ans = 0;
  for (int i = 1; i <= n - 1; i++) {
    if (find(i) != find(i + 1) && grt[find(i)] > i) {
      join(i, i + 1);
      ans++;
    }
  }
  printf("%d\n", ans);
}
