#include <bits/stdc++.h>
using namespace std;
int n, m, comp[200010], cc;
vector<int> g[200010];
pair<int, int> seg[200010];
void dfs(int u, int c) {
  comp[u] = c;
  seg[c].first = min(seg[c].first, u);
  seg[c].second = max(seg[c].second, u);
  for (auto v : g[u])
    if (!comp[v]) dfs(v, c);
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n >> m;
  for (int i = 1; i <= n; i++) seg[i] = {1000000007, 0};
  for (int i = 1; i <= m; i++) {
    int u, v;
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  for (int i = 1; i <= n; i++)
    if (!comp[i]) dfs(i, ++cc);
  sort(seg + 1, seg + cc + 1);
  int mx = 0, ans = 0;
  for (int i = 1; i <= cc; i++) {
    if (seg[i].first <= mx) ans++;
    mx = max(mx, seg[i].second);
  }
  cout << ans;
  return 0;
}
