#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> graph(200001);
int visited[200001];
int M = 0;
void dfs(int node, int parent) {
  M = max(M, node);
  for (auto child : graph[node]) {
    if (child == parent) continue;
    if (visited[child] == 0) {
      visited[child] = 1;
      dfs(child, node);
    }
  }
}
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int u, v;
    cin >> u >> v;
    graph[u].push_back(v);
    graph[v].push_back(u);
  }
  int ans = 0;
  visited[1] = 1;
  dfs(1, -1);
  for (int i = 1; i <= n; i++) {
    if (visited[i] == 0) {
      if (i < M) ans++;
      visited[i] = 1;
      dfs(i, -1);
    }
  }
  cout << ans;
}
