Greedy Algorithms8 sections · 316 units
Open in Course

Minimum Cover - Implementation

The code

function videoStitching(clips, T)
 sort clips by start ascending
 count := 0
 curEnd := 0
 i := 0
 while curEnd < T
 maxEnd := curEnd
 while i < length of clips and clips[i].start <= curEnd
 maxEnd := max(maxEnd, clips[i].end)
 i := i + 1
 if maxEnd = curEnd then
 return -1 // Cannot extend further
 curEnd := maxEnd
 count := count + 1
 return count

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