### PROBLEM LINK:

**Author:** Vivek Hamirwasia

**Tester:** Mahbub

**Editorialist:** Jingbo Shang

### DIFFICULTY:

Easy

### PREREQUISITES:

Sort, Greedy.

### PROBLEM:

Given some sets of open intervals (exclusive at two ends), for each set, find the maximum number of disjoint intervals.

### EXPLANATION:

First of all, we need to observe that the intervals in different sets are independent (in the original statement, the customers preferred in different compartments are independent).

For a single set, it is a classical greedy problem, called Activity Selection problem. The greedy method is as following:

- Sort the intervals by their right end ascending.
- Initialized the select intervals as an empty set
- Consider the sorted intervals one by one, add it if it is possible (only need to check the last select interval and the current one).

The intuition of this greedy is that, we need to make sure the space remained for the later intervals is as large as possible. The proof is also easy. For the first interval, we definite choose the interval which ends earliest. Otherwise, we can replace the first interval in the best solution with that earliest ended interval (with at least same best solution). Therefore, we can achieve the maximum interval selections with choosing the earliest ended interval. Recursively, we can see that the greedy is correct.

In summary, we can solve this problem in O(**N** log **N**), where **N** is the total number of intervals in all sets.

### AUTHORâ€™S AND TESTERâ€™S SOLUTIONS:

Authorâ€™s solution can be found here.

Testerâ€™s solution can be found here.