#include <bits/stdc++.h>
using namespace std;
template <typename X, typename Y>
void Min(X &x, Y y) {
  x = (x > y) ? y : x;
}
template <typename X, typename Y>
void Max(X &x, Y y) {
  x = (x < y) ? y : x;
}
const int N = 2e5 + 5;
int n, m;
vector<int> ad[N];
int a[N], dd[N], lt, pos[N];
int noi[N];
int ma[N];
void dfs(int i) {
  dd[i] = 1;
  pos[i] = lt;
  ma[lt] = max(ma[lt], i);
  for (auto &v : ad[i]) {
    if (!dd[v]) {
      dfs(v);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  cin >> n >> m;
  for (int i = 1; i <= m; ++i) {
    int u, v;
    cin >> u >> v;
    ad[u].push_back(v);
    ad[v].push_back(u);
  }
  for (int i = 1; i <= n; ++i)
    if (!dd[i]) {
      lt++;
      dfs(i);
    }
  int edge = 0;
  for (int i = 1; i <= n; ++i) {
    int v = pos[i], dem = 0;
    int top = ma[v];
    int j = i;
    while (j <= top) {
      int u = pos[j];
      top = max(top, ma[u]);
      if (!noi[u]) {
        noi[u] = 1;
        dem++;
      }
      j++;
    }
    edge += dem - 1;
    i = j - 1;
  }
  cout << edge;
}
