Editorial
Suppose an interval is completely contained in another interval. For any third interval, replacing the contained interval by the containing interval cannot decrease the length of the union. Therefore, contained intervals can be removed when searching for an optimum.
Sort the intervals by increasing , and for equal by decreasing . Scan from left to right and remove every interval whose is not larger than the maximum seen so far. Let the remaining intervals be
Then
Initialize the answer with the maximum length of any original interval. This also handles the case where every other interval is contained in one interval.
Now fix the right interval . Maintain with a two-pointer scan the boundary between earlier intervals satisfying and those satisfying .
If , interval is disjoint from interval , so the union length is
With a prefix maximum of interval lengths, the best value of this form is available immediately.
If , the two intervals overlap or touch. Since the right endpoints of the remaining intervals are strictly increasing, , so their union is
Thus, among all such , the best choice is the earliest one, which has the smallest .
Sorting takes time, and the filtering, prefix preprocessing, and two-pointer scan take time. The total time complexity is .
Every interval lies inside , so the union of any two intervals also lies inside this range. Therefore, the answer is at most and always fits in a signed 64-bit integer.
Solution written by GPT5.6