Greedy Algorithms8 sections · 316 units
Open in Course

Non-overlapping - Implementation

The code

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

Time: O(nlogn)O(n \log n). Space: O(1)O(1) extra.