Greedy Algorithms8 sections · 316 units
Open in Course

Non-overlapping - Implementation

The code

Here is the solution:

function eraseOverlapIntervals(intervals)
 if intervals is empty then
 return 0
 sort intervals by end time
 count := 1
 currentEnd := intervals[0].end
 for i from 1 to length - 1
 if intervals[i].start >= currentEnd then
 count := count + 1
 currentEnd := intervals[i].end
 return length - count

Time: O(nlogn)O(n \log n) for sorting. Space: O(1)O(1) extra if sorting in place.

The key is recognizing that removing minimum equals keeping maximum. Activity selection gives you the maximum.