#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 50;
const long long INF = 0x3f3f3f3f;
const long long mod = 1e9 + 7;
struct EDGE {
  int to, nex;
};
int head[maxn];
int cnt;
EDGE edge[maxn * 3];
int vis[maxn];
int val[maxn];
int dis[maxn];
vector<pair<int, int> > vec;
void addedge(int u, int v) {
  edge[++cnt] = EDGE{v, head[u]};
  head[u] = cnt;
}
void dfs(int u, int fa, int &weaker, int &big) {
  vis[u] = 1;
  weaker = min(weaker, u);
  big = max(big, u);
  for (int i = head[u]; i; i = edge[i].nex) {
    int v = edge[i].to;
    if (v == fa) continue;
    if (vis[v]) continue;
    dfs(v, u, weaker, big);
  }
}
int main(int argc, char *argv[]) {
  if (argc == 2 && strcmp("-debug", argv[1]) == 0) {
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
  }
  int n, m;
  cin >> n >> m;
  int u, v;
  for (int i = 1; i <= m; i++) {
    scanf("%d%d", &u, &v);
    addedge(u, v);
    addedge(v, u);
  }
  for (int i = 1; i <= n; i++) {
    if (vis[i]) continue;
    int big = i, weak = i;
    dfs(i, 0, weak, big);
    vec.push_back(make_pair(weak, big));
  }
  sort(vec.begin(), vec.end());
  int biggest = -1;
  int ans = 0;
  for (int i = 0; i < (int)vec.size(); i++) {
    if (vec[i].first <= biggest) ans++;
    biggest = max(biggest, vec[i].second);
  }
  cout << ans << endl;
  return 0;
}
