#include <bits/stdc++.h>
using namespace std;
long long n, m, chk[200020], ans;
vector<long long> G[200020];
long long st[200020], ed[200020];
set<long long> s;
void dfs(int x, int y) {
  chk[x] = y;
  for (long long w : G[x])
    if (!chk[w]) dfs(w, y);
}
int main() {
  ios::sync_with_stdio(false);
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    long long x, y;
    cin >> x >> y;
    G[x].push_back(y);
    G[y].push_back(x);
  }
  for (int i = 1; i <= n; i++)
    if (!chk[i]) dfs(i, i);
  for (int i = 1; i <= n; i++)
    if (!st[chk[i]])
      st[chk[i]] = ed[chk[i]] = i;
    else
      ed[chk[i]] = i;
  for (int i = 1, j; i <= n; i = j) {
    s.clear();
    for (j = i + 1; j < ed[i]; j++)
      if (chk[j] != i) {
        s.insert(chk[j]);
        ed[i] = max(ed[i], ed[chk[j]]);
      }
    ans += s.size();
  }
  cout << ans;
}
