KatInterview

Maximum Sum Window Over Sparse Value Ranges

Greedy & IntervalsAuto-graded · 25 test cases
MediumAuto-gradedGreedy & Intervalssliding-windowtwo-pointersintervals

Last updated

Find the largest sum of k consecutive positions when values are defined by disjoint intervals on an infinite line.

You have an infinite sequence of positions numbered 1, 2, 3, ... extending indefinitely. Each position holds some amount of value, determined by a set of non-overlapping intervals.

You are given intervals, where intervals[i] = [start, end, value] indicates that every position from start to end (inclusive) contains value units. Intervals never overlap or share positions. Any position not covered by an interval contains 0.

Your task is to select a contiguous window of exactly k positions and compute the sum of values at those positions. Return the maximum possible sum modulo 1,000,000,007.

Important: Compare the actual sums before applying the modulo operation. The modulo should only be applied to the final maximum value.

Constraints

  • 1 <= n <= 200,000 where n is the number of intervals
  • 1 <= start <= end <= 10^9 for each interval
  • 1 <= value <= 10^6 for each interval
  • 1 <= k <= 10^9
  • Intervals are disjoint (no two intervals share any position)
  • The intervals array may be given in any order
  • Actual sums before modulo can exceed 10^12 but stay within the range of 64-bit integers

Examples

Example 1

Input: max_sum_window(5, [[1, 4, 2], [6, 6, 5], [7, 7, 7], [9, 10, 1]])

Output: 16

Example 2

Input: max_sum_window(5, [[10, 12, 4], [3, 5, 1], [7, 8, 6]])

Output: 20

Example 3

Input: max_sum_window(1012, [[1, 1000, 1000000], [1001, 1012, 1], [5001, 6012, 988000]])

Output: 5

Hints

Hint 1

The optimal window must align with interval boundaries in a specific way. Consider windows that start at an interval's beginning or end at an interval's finish.

Hint 2

You cannot check every possible starting position since they range up to 10^9. Focus on the at most 2n candidate positions determined by interval endpoints.

Hint 3

Use a two-pointer technique to efficiently compute window sums for all candidate starting positions after sorting intervals by their left endpoint.