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