#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("sse4")
using namespace std;
template <class T>
bool ckmin(T& a, const T& b) {
  return b < a ? a = b, 1 : 0;
}
template <class T>
bool ckmax(T& a, const T& b) {
  return a < b ? a = b, 1 : 0;
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int MOD = 1000000007;
const char nl = '\n';
const int MX = 200003;
vector<int> g[MX];
int vis[MX];
vector<int> na(MX, MX), an(MX, 0);
void dfs(int u, int c) {
  vis[u] = c;
  an[c] = max(an[c], u);
  na[c] = min(na[c], u);
  for (auto i : g[u])
    if (!vis[i]) dfs(i, c);
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int n, m, u, v;
  vector<int> se(MX, 0);
  cin >> n >> m;
  for (int i = 0; i < (m); i++) {
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  int cn = 0;
  for (int i = 0; i < (n + 1); i++) {
    if (!vis[i]) {
      dfs(i, cn);
      cn += 1;
    }
  }
  map<int, int> x;
  map<int, int> y;
  for (int i = 1; i < cn; i++) {
    x[na[i]] = 1;
    y[an[i]] = 1;
  }
  int ed = 0, ct = 0;
  for (int i = 0; i < (n); i++) {
    if (x[i]) {
      ct += 1;
      if (ct > 1) ed += 1;
    }
    if (y[i]) {
      ct -= 1;
    }
  }
  cout << ed;
  return 0;
}
