#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
using ll = long long;
using db = long double;
using ii = pair<ll, ll>;
const ll N = 2e5 + 10, LG = 17, MOD = 998244353;
const ll SQ = 320;
const long double EPS = 1e-7;
ll p[N];
ll mx[N];
ll get(ll i) { return i == p[i] ? i : p[i] = get(p[i]); }
bool mrg(ll u, ll v) {
  u = get(u);
  v = get(v);
  if (u == v) return false;
  p[u] = v;
  mx[v] = max(mx[v], mx[u]);
  return true;
}
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  ll n, m;
  cin >> n >> m;
  iota(p, p + n + 1, 0);
  iota(mx, mx + n + 1, 0);
  for (ll i = 0; i < m; i++) {
    ll u, v;
    cin >> u >> v;
    mrg(u, v);
  }
  ll mx = 0;
  ll ans = 0;
  for (ll i = 1; i < n + 1; i++) {
    if (i <= mx) ans += mrg(i, i - 1);
    mx = max(mx, ::mx[get(i)]);
  }
  cout << ans << endl;
  return 0;
}
