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
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
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).
Thanks to the Editorial for clearing the sorting of the intervals
Comments
Post a Comment