#include <bits/stdc++.h>
using namespace std;
vector<long long int> adj[200005];
long long int comp = 0;
long long int visited[200005], mn[200005], mx[200005], num[200005], par[200005];
long long int parent(long long int i) {
  if (par[i] == 0)
    return i;
  else
    return parent(par[i]);
}
void dfs(long long int node) {
  if (visited[node] != 0) return;
  visited[node] = comp;
  mn[comp] = min(mn[comp], node);
  mx[comp] = max(mx[comp], node);
  for (auto it : adj[node]) dfs(it);
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long int n, m;
  cin >> n >> m;
  while (m--) {
    long long int u, v;
    cin >> u >> v;
    adj[v].push_back(u);
    adj[u].push_back(v);
  }
  for (long long int i = 1; i < n + 1; i++) {
    if (!visited[i]) {
      comp++;
      mx[comp] = i;
      mn[comp] = i;
      dfs(i);
    }
  }
  long long int ans = 0;
  long long int i = 1;
  while (i <= n) {
    long long int compp = parent(visited[i]);
    while (i <= mx[compp]) {
      long long int comppp = parent(visited[i]);
      if (compp != comppp) {
        ans++;
        par[comppp] = compp;
        mx[compp] = max(mx[compp], mx[comppp]);
        mn[compp] = min(mn[compp], mn[comppp]);
      }
      i++;
    }
  }
  cout << ans << '\n';
  return 0;
}
