Two Recorders

medium intervals greedy sorting 1000 ms · 256 MB

Two Recorders

Alice has a TV guide listing n shows airing today. The i-th show starts at minute s_i and ends at minute e_i, occupying every minute from s_i to e_i inclusive. Bob owns exactly two recorders. A recorder can record at most one show at a time, and once it starts recording a show it must capture every minute of it, from start to end — it cannot pause or switch mid-show. A recorder that finishes a show at minute t becomes free starting at minute t + 1: it may begin a show that starts at t + 1 or later, but not one that starts at t itself, since that would mean recording two shows during the same minute.

Bob gets to pick which shows to record, and on which of his two recorders, skipping any shows that don't fit. Help him find the maximum number of shows he can record in full.

Input

The first line contains a single integer n (1 ≤ n ≤ 2·10^5) — the number of shows.

Each of the next n lines contains two integers s_i and e_i (1 ≤ s_i ≤ e_i ≤ 10^9) — the start and end minute of the i-th show.

Output

Print a single integer — the maximum number of shows Bob can record in full.

Notes

Two shows assigned to the same recorder conflict if they share even a single minute — in particular, a show ending at minute t and a show starting at minute t cannot both go on that recorder, even though they don't share a full minute of airtime. Shows on different recorders never conflict with each other, no matter how they overlap.

In the first example, all three shows pairwise overlap or touch at minute 3, so at most two of them can ever be recorded; recording the first and second show (one per recorder) is one way to reach that maximum. In the second example, all four shows can be split between the two recorders so that none of them has to be dropped.

Example 1

Input

3
1 3
3 5
2 4

Output

2

Example 2

Input

4
1 4
2 3
4 6
5 7

Output

4

Hints · reveal one at a time if you're stuck

Hint 1

Two shows conflict when they share a minute, including when one ends at the minute the other starts. With only one recorder, which show should you keep next so that you leave the most room for the rest?

Hint 2

Consider the shows in order of their end time and track when each recorder becomes free. Ask what the recorder that can take a show does to the other recorder's future options.

Hint 3

The key decision is which recorder takes a show that fits on both. Give it to the recorder that became free most recently but still before the show starts, so the idle recorder stays available for shows that start earlier.

report an issue Prefer your own editor? sooks prep 63 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.