#include <bits/stdc++.h>
const long long MAXN = 1e6 + 1;
const long long MOD = 1e9 + 7;
using namespace std;
long long readInt() {
  bool minus1 = false;
  long long result = 0;
  char ch;
  ch = getchar();
  while (true) {
    if (ch == '-') break;
    if (ch >= '0' && ch <= '9') break;
    ch = getchar();
  }
  if (ch == '-')
    minus1 = true;
  else
    result = ch - '0';
  while (true) {
    ch = getchar();
    if (ch < '0' || ch > '9') break;
    result = result * 10 + (ch - '0');
  }
  if (minus1)
    return -result;
  else
    return result;
}
vector<int> g[MAXN];
int used[MAXN];
int color[MAXN];
int mn[MAXN];
int mx[MAXN];
int col = 0;
void dfs(int v) {
  color[v] = col;
  used[v] = 1;
  mn[color[v]] = min(mn[color[v]], v);
  mx[color[v]] = max(mx[color[v]], v);
  for (int i : g[v]) {
    if (!used[i]) {
      dfs(i);
    }
  }
}
int ans = 0;
int main() {
  int n = readInt(), m = readInt();
  for (int i = 1; i <= m; i++) {
    int v = readInt(), u = readInt();
    g[u].push_back(v);
    g[v].push_back(u);
  }
  for (int i = 1; i <= n; i++) {
    mn[i] = MOD;
    mx[i] = -MOD;
  }
  for (int i = 1; i <= n; i++) {
    if (!used[i]) {
      col++;
      dfs(i);
    }
  }
  vector<pair<int, int> > intervals;
  for (int i = 1; i <= col; i++) {
    intervals.push_back({mn[i], mx[i]});
  }
  sort(intervals.begin(), intervals.end());
  pair<int, int> cur = intervals[0];
  for (int i = 1; i < intervals.size(); i++) {
    if (cur.second >= intervals[i].first) {
      ans++;
      cur.second = max(cur.second, intervals[i].second);
    } else {
      cur = intervals[i];
    }
  }
  cout << ans;
  return 0;
}
