Maximum Non-overlapping IntervalsMedium

Maximum Non-overlapping Intervals

MediumPractice library · +20 XPgreedysortingintervals

Given a list of N intervals, where each interval is represented by a start time and an end time, find the maximum number of non-overlapping intervals that can be selected. Two intervals are considered overlapping if they share any common time, including endpoints. If two intervals end at the same time, only one can be chosen if they are to be considered non-overlapping with a subsequent interval. We want to maximize the count of selected intervals.

Input

The first line contains an integer N, the number of intervals. The next N lines each contain two integers, the start time and end time of an interval.

Output

Print a single integer representing the maximum number of non-overlapping intervals.

Constraints

1 <= N <= 200000, 0 <= start_i <= end_i <= 10^9

Time limit 2 s (native code; slower languages get more)Memory 256 MB14 hidden tests

Example 1

Input
5
1 3
2 4
3 5
4 6
5 7
Output
3

Select intervals (1,3), (3,5), (5,7) for a total of 3.

Example 2

Input
4
1 2
2 3
3 4
1 5
Output
3

Select intervals (1,2), (2,3), (3,4) for a total of 3.

Hints