KatInterview

Maximum Coverage From Non-Overlapping Intervals

Greedy & IntervalsAuto-graded · 15 test cases
MediumAuto-gradedGreedy & Intervalsgreedyintervalssorting

Last 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:

  1. Merge all overlapping or touching intervals into disjoint merged intervals. Two intervals [a, b] and [c, d] touch if b == c.
  2. From the resulting list of disjoint merged intervals, pick at most k of them to maximise the total covered length (sum of end - start for each chosen interval).
  3. 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 intervals is empty or k == 0, return 0.
  • 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.