Pay attention to the proposed naive quadratic solution: you will need to consider each point as the beginning of an interval or the end of an interval.
I'm not sure if this is the optimal solution, but it is better than the naive quadratic:
Name the points {P1, ..., Pn}.
Since any point must be covered by at least one interval, find all the intervals that can span the point P1 (suppose that the interval either begins with Pi or ends in Pi). For each of these intervals, continue eagerly, as in the linear timeline.
To optimize it further, instead of starting with P1, we need to find the best starting point - this will be a point that can be covered with a minimum number of intervals. I do not know if we can do this in linear time, but a good heuristic may be to start with the fact that the sum of its distances from its two neighbors is maximum.
Edit: O (nlogn) way to find the best starting point:
We can build a list of possible 2n segments (for any point Pi, the interval can start with Pi or end in Pi). Then insert these intervals into the segment tree.
Do not use a regular segment tree, but instead of storing intervals in canonical subsets, just save their number (see the notes section in the Wikipedia article).
The tree structure will take O (nlogn) time. Now, for each Pi point, count the number of segments (intervals) into which it falls. This will take O (logn) for each point or O (nlogn) total.
Select a point with the minimum number of intervals. For each of the intervals, continue with the greedy approach as described above.
Lior kogan
source share