Wednesday, July 19th

 Finding non-overlapping intervals is the subject of today's problem

Given an array of intervals, find the minimum number of intervals needed to remove in order to have the remaining intervals non-overlapping

The idea is to sort the intervals based on ending time, then greedily choose each intervals with the interval with the earlier end time

First we sort the intervals.  To sort on end time we will need a custom comparator

    bool customCompare(vector<int>& v1, vector<int>& v2) {
    return v1[1] < v2[1];
    }

Then call sort

    sort( intervals.begin(), intervals.end(), customCompare );     

Initialize 2 variables, one to count the number of intervals to remove, and a second to track the end of the most recent interval

int count=0;
int end=INT_MIN;

Then iterate through each interval.  Get the start and end of the current interval.  If the end of the start of the current interval is after the end of the previously tracked interval, update end.  Otherwise, increment the number of intervals to remove (since the interval overlaps with a previous ending).

    int x,y;
for(int i=0; i<intervals.size(); i++) {
x=intervals[i][0];
y=intervals[i][1];

     x>=end ? end=y : count++;
}
return count;

Thanks to the Editorial for clearing the sorting of the intervals

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th