#include <bits/stdc++.h>
using namespace std;
int fa[202000];
int findd(int x) {
  if (fa[x] == x) return x;
  return fa[x] = findd(fa[x]);
}
void make(int x, int y) {
  x = findd(x);
  y = findd(y);
  if (x < y)
    fa[x] = y;
  else
    fa[y] = x;
}
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 1; i <= n; i++) fa[i] = i;
  while (m--) {
    int x, y;
    cin >> x >> y;
    make(x, y);
  }
  int cnt = 0;
  for (int i = 1; i <= n; i++) {
    int x = findd(i);
    while (i < x) {
      int y = findd(i);
      if (y < x) {
        cnt++;
        fa[y] = x;
      }
      if (y > x) {
        cnt++;
        fa[x] = y;
        x = y;
      }
      i++;
    }
  }
  cout << cnt << "\n";
  return 0;
}
