#include <bits/stdc++.h>
using namespace std;
vector<int> adj[200005];
int cc[200005];
int vis[200005];
int cmpnt;
int node_max[200005];
vector<int> cc1[200005];
int mx;
void dfs(int u) {
  vis[u] = 1;
  cc[u] = cmpnt;
  cc1[cmpnt].push_back(u);
  mx = max(mx, u);
  for (auto v : adj[u]) {
    if (!vis[v]) dfs(v);
  }
}
int main() {
  int n, m;
  scanf("%d %d", &n, &m);
  for (int i = 0; i < m; i++) {
    int a, b;
    scanf("%d %d", &a, &b);
    adj[a].push_back(b);
    adj[b].push_back(a);
  }
  cmpnt = 1;
  for (int i = 1; i <= n; i++) {
    mx = INT_MIN;
    if (!vis[i]) dfs(i);
    node_max[cmpnt] = mx;
    cmpnt++;
  }
  int ans = 0;
  int node_no = 1;
  while (node_no <= n) {
    int now_cmp = cc[node_no];
    int now_mx = node_max[now_cmp];
    while (node_no <= now_mx) {
      if (cc[node_no] == now_cmp) {
        node_no++;
        continue;
      }
      ans++;
      int ccc = cc[node_no];
      now_mx = max(now_mx, node_max[ccc]);
      for (auto v : cc1[ccc]) {
        cc[v] = now_cmp;
      }
      node_no++;
    }
  }
  cout << ans;
  return 0;
}
