#include <bits/stdc++.h>
using namespace std;
int mini, maxi, rebra, u0, v0, numbers, res, br;
vector<int> adj[200002];
vector<pair<int, int> > a;
bool used[200002];
void dfs(int v) {
  used[v] = 1;
  maxi = max(maxi, v);
  for (int i = 0; i < adj[v].size(); i++) {
    if (used[adj[v][i]] == 0) {
      dfs(adj[v][i]);
    }
  }
}
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    cin >> u0 >> v0;
    adj[u0].push_back(v0);
    adj[v0].push_back(u0);
  }
  for (int i = 1; i <= n; i++) {
    maxi = -1;
    if (used[i] == 0) {
      dfs(i);
      a.push_back(make_pair(i, maxi));
    }
  }
  sort(a.begin(), a.end());
  int right = a[0].second;
  for (int i = 1; i < a.size(); i++) {
    if (a[i].first < right) {
      br++;
    }
    if (a[i].second > right) {
      right = a[i].second;
    }
  }
  cout << br << endl;
}
