#include <stdio.h>
#include <stdlib.h>
// Structure to represent an interval
typedef struct {
int start;
int end;
} Interval;
// Comparator function to sort intervals by end time
int compare(const void *a, const void *b) {
Interval *i1 = (Interval *)a;
Interval *i2 = (Interval *)b;
return i1->end - i2->end;
}
// Function to find minimum number of intervals to remove
int eraseOverlapIntervals(Interval* intervals, int intervalsSize) {
if (intervalsSize == 0) return 0;
// Sort intervals by their end time
qsort(intervals, intervalsSize, sizeof(Interval), compare);
int count = 0; // count of removed intervals
int end = intervals[0].end; // end time of last selected interval
for (int i = 1; i < intervalsSize; i++) {
if (intervals[i].start < end) {
// Overlap found, remove this interval
count++;
} else {
// No overlap, update end to current interval's end
end = intervals[i].end;
}
}
return count;
}
int main() {
Interval intervals[] = {{1,3}, {2,4}, {3,5}};
int size = sizeof(intervals) / sizeof(intervals[0]);
int removals = eraseOverlapIntervals(intervals, size);
printf("Minimum removals: %d\n", removals);
return 0;
}
qsort(intervals, intervalsSize, sizeof(Interval), compare);
Sort intervals by their end time to prioritize earliest finishing
int end = intervals[0].end;
Initialize end to the end time of the first interval selected
if (intervals[i].start < end) { count++; } else { end = intervals[i].end; }
If current interval overlaps, increment removal count; else update end to current interval's end