Painting the fence
InterviewTime limit2sMemory limit512 MB
Pick a pairwise non-overlapping set of intervals to cover as many of the n slats as possible, then report the number left unpainted.
- Level
Medium6 of 10
- Topics
- Sorting, Dynamic programming, Binary search, Prefix sum
- Solved
- No attempts yet
Problem
You are painting a picket fence made of slats, numbered 1 to . Each of painters has offered to paint one fixed range of slats. They dislike each other, so a painter refuses the job if another painter's range overlaps their own range by even one slat.
Choose a set of painters whose ranges do not overlap, so that the number of unpainted slats is as small as possible. Suppose the fence has 8 slats and there are 3 painters, who want to paint slats 1 to 3, 2 to 6, and 5 to 8. Picking the first painter and the third painter creates no overlap and leaves only slat 4 unpainted.
Input
Each input consists of a single test case, and the same program may be run several times on different inputs. The first line contains two integers and (, ), where is the number of slats and is the number of painters. Each of the next lines contains two integers and (), meaning that this painter wants to paint every slat from to , inclusive.
Output
Print one integer, the smallest number of slats that stay unpainted when the painters are chosen optimally without overlap.