CP: The busiest moment

A cafe records when each guest arrives and leaves. A guest is inside from the arrival minute to the leaving minute, both included. Find the largest number of guests inside at one time, and the first minute when that happens.

What to build

Treat each guest as a range addition of 1 over a..b. Use a difference array over the minutes 1 to 100000, then scan with a running sum and remember the first minute with the largest value.

Requirements

  • Use a difference array over the minutes
  • Print MAX MINUTE: the largest count and the earliest minute with that count
  • Minutes are between 1 and 100000

Input

The first line has n. Each of the next n lines has a b (1 ≤ a ≤ b ≤ 100000).

Output

MAX MINUTE on one line.

Constraints

1 ≤ n ≤ 100,000.

Example

Input:

3
1 5
3 8
4 6

Output:

3 4

Why it works

Each guest adds 1 on every minute from a to b, which is a range update. Rebuilding with a running sum gives the number of guests at each minute. Replacing the best only when a value is strictly larger keeps the earliest minute.

Examples

Example 1 · Input
3
1 5
3 8
4 6
Expected output
3 4
Example 2 · Input
2
1 2
3 4
Expected output
1 1

Hints

Hint 1

vector<int> diff(100002, 0); diff[a]++; diff[b + 1]--;

Hint 2

Scan minutes 1 to 100000 with cur += diff[t].

Hint 3

Update the best only when cur > best (strictly), so the first minute stays.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> diff(100002, 0);
    int last = 1;
    for (int i = 0; i < n; i++) {
        int a, b;
        cin >> a >> b;
        diff[a]++;
        diff[b + 1]--;
        if (b > last) last = b;
    }
    int cur = 0, best = 0, bestMinute = 1;
    for (int t = 1; t <= last; t++) {
        cur += diff[t];
        if (cur > best) {
            best = cur;
            bestMinute = t;
        }
    }
    cout << best << " " << bestMinute << "\n";
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Difference arrays →