#include <bits/stdc++.h>
using namespace std;
const int mxN = 2e5 + 10;
int n, m;
vector<vector<int> > edges(mxN);
vector<bool> visited(mxN);
int Highest;
void dfs(int node) {
  Highest = max(Highest, node);
  visited[node] = true;
  for (auto child : edges[node]) {
    if (!visited[child]) {
      dfs(child);
    }
  }
  return;
}
int main() {
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int u, v;
    cin >> u >> v;
    edges[u].push_back(v);
    edges[v].push_back(u);
  }
  Highest = 0;
  int cnt = 0;
  for (int i = 1; i <= n; i++) {
    if (!visited[i]) {
      if (Highest && Highest > i) {
        ++cnt;
      }
      dfs(i);
    }
  }
  cout << cnt << "\n";
  return 0;
}
