All problems

Problem 245

Maximum Non-Overlapping Meetings

Medium · 20 pts · Array, Greedy, Sorting

Problem

You are given N meetings, each as an interval [start, end], and a single meeting room. Choose as many meetings as possible to hold in the room so that no two chosen meetings conflict. Two meetings conflict if they share any moment, including the boundary, so a meeting ending at time t conflicts with one starting at time t. The classic greedy approach: sort the meetings by end time and pick each meeting that starts strictly after the end of the last meeting picked. Finishing as early as possible always leaves the most room for later meetings.

Input

First line: N. Next N lines: start and end of a meeting.

Output

Print the maximum number of meetings.

Constraints

1 <= N <= 100000; 0 <= start < end <= 1000000000

Example input

6
1 2
3 4
0 6
5 7
8 9
5 9

Example output

4

Explanation

Sorted by end time, pick [1, 2], then [3, 4], then [5, 7] (since [0, 6] overlaps), then [8, 9]. The meeting [5, 9] would overlap [5, 7]. That gives 4 meetings.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Lemonade Change Next: Minimum Arrows to Burst Balloons