#include <bits/stdc++.h>
using namespace std;
template <typename IntType>
void read(IntType& val) {
  val = 0;
  int c;
  bool inv = false;
  while (!isdigit(c = getchar()))
    if (c == '-') inv = true;
  do {
    val = (val << 1) + (val << 3) + c - '0';
  } while (isdigit(c = getchar()));
  if (inv) val = -val;
}
const int MaxN = 200000 + 10, MaxM = 200000 + 10;
int n, m;
vector<int> h[MaxN];
int bcnt, bid[MaxN];
pair<int, int> blr[MaxN];
void addedge(int u, int v) {
  h[u].push_back(v);
  h[v].push_back(u);
}
void dfs(int u, int id) {
  bid[u] = id;
  blr[id].first = min(blr[id].first, u);
  blr[id].second = max(blr[id].second, u);
  for (int v : h[u]) {
    if (bid[v] == 0) dfs(v, id);
  }
}
int main(int argc, char* argv[]) {
  read(n);
  read(m);
  for (int i = 1; i <= m; i++) {
    int u, v;
    read(u);
    read(v);
    addedge(u, v);
  }
  for (int i = 1; i <= n; i++) {
    if (bid[i] == 0) {
      bcnt++;
      blr[bcnt].first = n + 1;
      dfs(i, bcnt);
      ;
    }
  }
  sort(blr + 1, blr + bcnt + 1);
  int ans = 0;
  int i = 1;
  while (i <= bcnt) {
    int l = blr[i].first, r = blr[i].second;
    ;
    i++;
    while (i <= bcnt && blr[i].first <= r) {
      ;
      r = max(r, blr[i].second);
      ans++;
      i++;
    }
  }
  printf("%d\n", ans);
  return 0;
}
