#include <bits/stdc++.h>
using namespace std;
set<int> st;
int mx;
vector<int> p[200005], vis(200005);
void dfs(int i) {
  vis[i] = 1;
  mx = max(mx, i);
  st.erase(i);
  for (auto x : p[i]) {
    if (!vis[x]) {
      dfs(x);
    }
  }
}
void solve() {
  int n, m;
  cin >> n >> m;
  while (m--) {
    int x, y;
    cin >> x >> y;
    p[x].push_back(y);
    p[y].push_back(x);
  }
  for (int i = 1; i < n + 1; i++) {
    st.insert(i);
  }
  int cnt = 0;
  for (int i = 1; i < n + 1; i++) {
    mx = 0;
    if (!vis[i]) {
      dfs(i);
    }
    while ((int)((st).size())) {
      if (*st.begin() > mx) {
        break;
      }
      cnt++;
      dfs(*st.begin());
    }
  }
  cout << cnt;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int test_cases;
  test_cases = 1;
  while (test_cases--) {
    solve();
  }
  return 0;
}
