#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
int n, m;
struct node {
  int v, to;
} edges[maxn << 1];
int head[maxn], cnt;
int l, r, vis[maxn];
void dfs(int rt) {
  vis[rt] = 1;
  for (int i = head[rt]; i; i = edges[i].to) {
    if (!vis[edges[i].v]) {
      l = min(l, edges[i].v), r = max(r, edges[i].v);
      dfs(edges[i].v);
    }
  }
}
vector<pair<int, int> > pp;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m;
  for (int i = 0, u, v; i < m; ++i) {
    cin >> u >> v;
    edges[++cnt] = {v, head[u]};
    head[u] = cnt;
    edges[++cnt] = {u, head[v]};
    head[v] = cnt;
  }
  for (int i = 1; i <= n; ++i) {
    if (vis[i]) continue;
    l = r = i;
    dfs(i);
    pp.push_back({l, r});
  }
  sort(pp.begin(), pp.end());
  l = r = -1;
  int ans = 0;
  for (auto it : pp) {
    int ll = it.first, rr = it.second;
    if (ll > r) {
      l = ll, r = rr;
    } else {
      ++ans;
      r = max(r, rr);
    }
  }
  cout << ans << endl;
  return 0;
}
