[LeetCode] Divide Intervals Into Minimum Number of Groups

2406. Divide Intervals Into Minimum Number of Groups

You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti].

You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other.

Return the minimum number of groups you need to make.

Two intervals intersect if there is at least one common number between them. For example, the intervals [1, 5] and [5, 8] intersect.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int minGroups(vector<vector<int>>& A) {
sort(begin(A), end(A));
priority_queue<int, vector<int>, greater<int>> q;
int res = 0;
for(int i = 0; i < A.size(); i++){
int s = A[i][0], e = A[i][1];
while(!q.empty() and q.top() < s) q.pop();
q.push(e);
res = max(res, (int)q.size());
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/11/PS/LeetCode/divide-intervals-into-minimum-number-of-groups/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.