#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
const int oo = 1e9 + 7;
vector<int> ins[N], rem[N];
int p[N], sub[N], mx[N], mn[N];
int root(int u) {
  while (p[u] != u) {
    p[u] = p[p[u]];
    u = p[u];
  }
  return u;
}
bool merge(int uu, int vv) {
  int u = root(uu), v = root(vv);
  if (u == v) return false;
  if (sub[u] < sub[v]) swap(u, v);
  mx[u] = max(mx[u], mx[v]);
  mn[u] = min(mn[u], mn[v]);
  sub[u] += sub[v];
  p[v] = u;
  return true;
}
void solve() {
  int n, m, i, x, y;
  cin >> n >> m;
  x = n;
  for (i = 1; i <= n; i++) {
    p[i] = i;
    sub[i] = 0;
    mx[i] = mn[i] = i;
  }
  for (i = 1; i <= m; i++) {
    int u, v;
    cin >> u >> v;
    if (merge(u, v)) x--;
  }
  y = x;
  int curr = 0;
  for (i = 1; i <= n; i++)
    if (p[i] == i) {
      rem[mx[i]].push_back(i);
      ins[mn[i]].push_back(i);
    }
  set<int> st;
  for (i = 1; i <= n; i++) {
    for (auto it : ins[i]) {
      if (!st.empty()) {
        if (merge(*st.begin(), it)) y--;
      }
      st.insert(it);
    }
    for (auto it : rem[i]) st.erase(it);
  }
  cout << x - y << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  int t = 1;
  while (t--) solve();
  return 0;
}
