#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > interval;
vector<int> adj[200007];
bool visited[200007];
void dfs(int i, int& l, int& r) {
  visited[i] = 1;
  l = min(i, l);
  r = max(i, r);
  for (int j : adj[i]) {
    if (!visited[j]) {
      dfs(j, l, r);
    }
  }
}
int main() {
  int n, e;
  cin >> n >> e;
  for (int i = 0; i < e; i++) {
    int u, v;
    cin >> u >> v;
    adj[--v].push_back(--u);
    adj[u].push_back(v);
  }
  for (int i = 0; i < n; i++) {
    if (!visited[i]) {
      int l = i, r = i;
      dfs(i, l, r);
      interval.push_back(make_pair(l, r));
    }
  }
  int end = INT_MIN, ans = 0;
  for (auto iPair : interval) {
    if (iPair.first <= end) {
      ans++;
    }
    end = max(end, iPair.second);
  }
  cout << ans;
  return 0;
}
