#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

/**
 * Logic Function: O(N) using Difference Array
 */
int findMaxPeople(int n, const vector<pair<int, int>>& requirements) {
    // Size n + 1 allows index n to be accessed safely
    vector<int> diff(n + 1, 0);

    for (int i = 0; i < n; ++i) {
        int start = requirements[i].first + 1;
        int end = requirements[i].second + 1;

        if (start <= n) {
            diff[start]++;
            if (end + 1 <= n) {
                diff[end + 1]--;
            }
        }
    }

    int max_people = 0;
    int current_willing = 0;

    for (int i = 1; i <= n; ++i) {
        current_willing += diff[i];
        // If 'current_willing' people are okay with group size 'i'
        if (current_willing >= i) {
            max_people = i;
        }
    }

    return max_people;
}

int main() {
    // Example Input:
    // 6 people
    // 1 2 -> Range [2, 3]
    // 1 4 -> Range [2, 5]
    // 0 3 -> Range [1, 4]
    // 0 1 -> Range [1, 2]
    // 3 4 -> Range [4, 5]
    // 0 2 -> Range [1, 3]
    
    int n = 6;
    vector<pair<int, int>> requirements = {
        {1, 2}, {1, 4}, {0, 3}, {0, 1}, {3, 4}, {0, 2}
    };

    int result = findMaxPeople(n, requirements);
    
    cout << "Maximum group size: " << result << endl;

    return 0;
}