#include <bits/stdc++.h>
using namespace std;
typedef int def;
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& v) {
  if (!v.empty()) {
    std::copy(v.begin(), v.end(), std::ostream_iterator<T>(out, " "));
  }
  return out;
}
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::set<T>& v) {
  if (!v.empty()) {
    std::copy(v.begin(), v.end(), std::ostream_iterator<T>(out, " "));
  }
  return out;
}
const int N = 2e5 + 10;
const long long M = 1e9 + 7;
int R[N], Par[N], Min[N], Max[N];
int ans = 0;
int parent(int n) {
  if (n == Par[n]) return n;
  return Par[n] = parent(Par[n]);
}
void join(int a, int b) {
  a = parent(a);
  b = parent(b);
  if (a == b) return;
  ans++;
  Min[a] = min(Min[a], Min[b]);
  Min[b] = min(Min[a], Min[b]);
  Max[a] = max(Max[a], Max[b]);
  Max[b] = max(Max[a], Max[b]);
  if (R[a] > R[b]) {
    Par[b] = a;
  } else {
    if (R[b] == R[a]) R[b]++;
    Par[a] = b;
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n, m;
  cin >> n >> m;
  for (def i = 1; i <= (n); i++) Par[i] = i;
  for (def i = 1; i <= (n); i++) Min[i] = i;
  for (def i = 1; i <= (n); i++) Max[i] = i;
  for (def i = 0; i < (m); i++) {
    int a, b;
    cin >> a >> b;
    join(a, b);
  }
  int init = ans;
  for (def i = 1; i <= (n); i++) {
    if (Min[parent(i)] == i) {
      int cur = i;
      while (Max[parent(i)] >= cur) {
        join(i, cur);
        cur++;
      }
    }
  }
  cout << ans - init;
}
