2406. Divide the interval into the minimum number of groups-difference groups

2406. Divide the interval into the minimum number of groups-difference groups

Give you a two-dimensional integer array intervals, where intervals[i] = [lefti, righti] represents the closed interval [lefti, righti].

You need to divide intervals into one or more interval groups. Each interval only belongs to one group, and any two intervals in the same group do not intersect.

Please return the minimum number of groups that need to be divided.

Two intervals are said to intersect if they cover overlapping ranges (that is, have at least one number in common). Let's say the intervals [1, 5] and [5, 8] intersect.

Example 1:

Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]] Output
: 3
Explanation: We can divide the interval into the following interval groups :

  • Group 1: [1, 5], [6, 8].
  • Group 2: [2, 3], [5, 10].
  • Group 3: [1, 10].
    It can be shown that the interval cannot be divided into less than 3 groups.

Example 2:

Input: intervals = [[1,3],[5,6],[8,10],[11,13]]
Output: 1
Explanation: All intervals are disjoint, so we can put them all in one group Inside.

This problem is solved using difference arrays.
The solution code is as follows:


#define size 1000005




int minGroups(int** intervals, int intervalsSize, int* intervalsColSize){
    
    

int a[size];
for(int i=0;i<size;i++){
    
    
    a[i]=0;
}
for(int i=0;i<intervalsSize;i++){
    
    
    a[intervals[i][0]]=a[intervals[i][0]]+1;
    a[intervals[i][1]+1]=a[intervals[i][1]+1]-1;


}
int re=0;
int m=a[0];
for(int i=1;i<size;i++){
    
    
    m=m+a[i];
    re=fmax(re,m);



}
return re;
  

}

Guess you like

Origin blog.csdn.net/weixin_43327597/article/details/133269577