#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
const long long mod = 1e9 + 7;
const long long NM = 2e18;
const int dx[] = {0, 1, 0, -1};
const int dy[] = {1, 0, -1, 0};
using namespace std;
int t, n, m, conectat[200005], viz[200005];
vector<int> v[200005];
int mn = NM, mx = -NM;
void dfs(int i) {
  viz[i] = 1;
  conectat[i] = 0;
  mn = min(mn, i);
  mx = max(mx, i);
  for (auto it : v[i]) {
    if (!viz[it]) {
      dfs(it);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m;
  while (m--) {
    int x, y;
    cin >> x >> y;
    v[x].push_back(y);
    v[y].push_back(x);
    conectat[x] = 1;
    conectat[y] = 1;
  }
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    if (!conectat[i]) continue;
    mn = NM, mx = -NM;
    dfs(i);
    long long inceput = mn;
    long long terminat = mx;
    for (int j = inceput; j <= terminat; j++) {
      if (!viz[j]) {
        ans++;
        dfs(j);
        if (terminat < mx) terminat = mx;
        if (inceput > mn) j = mn;
      }
    }
    for (int i = 1; i <= n; i++) {
      viz[i] = 0;
    }
  }
  cout << ans << '\n';
}
