Maximum Coverage From Non-Overlapping Intervals
Greedy & IntervalsAuto-graded · 15 test casesLast updated
Tests ability to merge overlapping intervals and use a greedy sweep to find the maximum total length covered by selecting at most K non-overlapping merged segments.
Maximum Coverage From Non-Overlapping Intervals
You are given a list of intervals representing time windows during which a sensor is active. Each interval is a pair [start, end] where start < end. Intervals may overlap or be nested.
Your goal is to select at most k non-overlapping intervals (after merging all overlapping ones) that together cover the maximum total length of the time axis.
More precisely:
- Merge all overlapping or touching intervals into disjoint merged intervals. Two intervals
[a, b]and[c, d]touch ifb == c. - From the resulting list of disjoint merged intervals, pick at most
kof them to maximise the total covered length (sum ofend - startfor each chosen interval). - Return that maximum total covered length as an integer.
Notes:
- If there are fewer merged intervals than
k, you may (and should) pick all of them. - If
intervalsis empty ork == 0, return0. - Interval lengths are always positive integers after merging.
Constraints
0 <= len(intervals) <= 2000- Each interval satisfies
0 <= start < end <= 10^6 1 <= k <= 2000- All coordinate values are integers.
Examples
Example 1
Input: max_coverage([[1, 5], [3, 8], [10, 14], [13, 18]], 2)
Output: 15
Example 2
Input: max_coverage([[0, 3], [1, 2], [5, 7]], 1)
Output: 3
Example 3
Input: max_coverage([], 3)
Output: 0
Hints
Hint 1
First sort the intervals by start time, then merge all overlapping or touching intervals into a list of disjoint segments — this is the classic interval-merge sweep.
Hint 2
After merging, each resulting segment is independent. To maximise total coverage with at most k picks, you want the k longest segments (greedy exchange argument: swapping a shorter segment for a longer one never decreases the total).
Hint 3
Sort the merged segment lengths in descending order and sum the first min(k, len(merged)) of them.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Step 1 — Merge Overlapping Intervals
Sort all intervals by their start coordinate. Then sweep through them left-to-right, extending the current open segment whenever the next interval's start is at or before the current end (overlapping or touching). When there is a genuine gap, close the current segment and record its length (end − start).
This is the standard O(n log n) interval-merge algorithm and yields a list of disjoint segment lengths.
Why correctness is not affected by merging first: picking any sub-portion of overlapping intervals can never beat picking the full merged segment, so we lose nothing by merging.
Step 2 — Greedy Selection of the k Longest Segments
After merging, the segments are independent (no overlap). We want to choose at most k of them to maximise the sum of lengths.
Exchange argument: Suppose an optimal solution skips a segment of length L_big and includes a segment of length L_small < L_big. Swapping them strictly increases the total — contradiction. Therefore, the greedy strategy of always taking the longest available segments is optimal.
Sort the merged lengths descending and sum the first min(k, len(merged)) values.
Edge Cases
- Empty input or
k == 0→ return0. - Fewer merged segments than
k→ take all of them. - All intervals overlap into one → returns that single segment's length if
k >= 1.
Complexity
| Step | Time | Space |
|---|---|---|
| Sort input | O(n log n) | O(n) |
| Merge sweep | O(n) | O(n) |
| Sort lengths + prefix sum | O(m log m) ≤ O(n log n) | O(m) |
| Total | O(n log n) | O(n) |
where n = len(intervals) and m ≤ n is the number of merged segments.
from typing import List
def max_coverage(intervals: List[List[int]], k: int) -> int:
if not intervals or k == 0:
return 0
# Step 1: sort by start, then merge overlapping/touching intervals
sorted_ivs = sorted(intervals, key=lambda x: x[0])
merged = []
cur_start, cur_end = sorted_ivs[0]
for start, end in sorted_ivs[1:]:
if start <= cur_end: # overlapping or touching
cur_end = max(cur_end, end)
else:
merged.append(cur_end - cur_start)
cur_start, cur_end = start, end
merged.append(cur_end - cur_start)
# Step 2: greedily pick the k longest merged segments
merged.sort(reverse=True)
return sum(merged[:k])