#include <bits/stdc++.h>
using namespace std;
long long int gcd(long long int a, long long int b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
long long int lcm(long long int a, long long int b) {
  return a * b / gcd(a, b);
}
long long int fexp(long long int a, long long int b) {
  long long int ans = 1;
  while (b) {
    if (b & 1) ans = ans * a % 1000000007;
    b /= 2;
    a = a * a % 1000000007;
  }
  return ans;
}
long long int inverse(long long int a, long long int p) {
  return fexp(a, p - 2);
}
void ingraph(vector<vector<long long int> >& graph, long long int m) {
  long long int x, y;
  for (long long int i = 0; i < m; i++) {
    cin >> x >> y;
    x--, y--;
    graph[x].push_back(y);
    graph[y].push_back(x);
  }
}
bool visited[2000005] = {0};
long long int dfs(vector<vector<long long int> >& graph, long long int v) {
  stack<long long int> st;
  st.push(v);
  long long int sz = 0;
  long long int mx = -1;
  visited[v] = 1;
  while (!st.empty()) {
    long long int u = st.top();
    if (u > mx) mx = u;
    st.pop();
    for (long long int i = 0; i < graph[u].size(); i++) {
      if (!visited[graph[u][i]]) {
        st.push(graph[u][i]);
        visited[graph[u][i]] = 1;
      }
    }
    sz++;
  }
  return mx;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long int t;
  t = 1;
  while (t--) {
    long long int n, m;
    cin >> n >> m;
    vector<vector<long long int> > graph(n);
    ingraph(graph, m);
    vector<pair<long long int, long long int> > vec;
    for (long long int i = 0; i < n; i++) {
      if (!visited[i]) {
        vec.push_back(make_pair(i, dfs(graph, i)));
      }
    }
    long long int cnt = 0;
    long long int y = vec[0].second;
    for (long long int i = 1; i < vec.size(); i++) {
      if (vec[i].first > y) {
        y = vec[i].second;
      } else {
        cnt++;
        y = max(y, vec[i].second);
      }
    }
    cout << cnt << endl;
  }
}
