Maximum Sum Window Over Sparse Value Ranges
Greedy & IntervalsAuto-graded · 25 test casesLast 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,000wherenis the number of intervals1 <= start <= end <= 10^9for each interval1 <= value <= 10^6for each interval1 <= 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^12but 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The challenge is that we cannot iterate through all possible starting positions since they range up to 10^9. The key insight is that an optimal window must be aligned with interval boundaries in one of two ways:
- The window starts at the beginning of some interval
- The window ends at the finish of some interval
This gives us at most 2n candidate positions to check instead of 10^9.
Finding left-aligned candidates: After sorting intervals by their starting positions, we use a two-pointer sweep. For each interval's start position as a potential window start, we:
- Maintain a running sum of all intervals completely contained within the window
- Add a partial contribution from any interval that is only partially covered at the window's right edge
- Update our running sum as we slide the window to the next candidate
Finding right-aligned candidates: To handle windows that should end at an interval's right boundary, we mirror the entire number line by negating all positions. A window ending at position r becomes a window starting at position -r. We run the same sweep on this mirrored view.
Why this is correct: Between any two aligned positions, the window's gain from shifting right (adding a new position at the right edge) minus its loss (removing a position at the left edge) either increases monotonically or decreases monotonically. This means the maximum in any unaligned region must occur at the boundary, which is an aligned position.
Modulo handling: We compare exact sums to find the maximum, then apply modulo only to the final result. Applying modulo during comparison would be incorrect since a larger true sum can have a smaller remainder.
Complexity
- Time: O(n log n) for sorting the intervals, plus O(n) for each of two linear sweeps
- Space: O(n) for storing sorted and mirrored interval data
Solution
from typing import List
def max_sum_window(k: int, intervals: List[List[int]]) -> int:
n = len(intervals)
left_endpoints = [interval[0] for interval in intervals]
sorted_indices = sorted(range(n), key=left_endpoints.__getitem__)
L = [left_endpoints[i] for i in sorted_indices]
R = [intervals[i][1] for i in sorted_indices]
V = [intervals[i][2] for i in sorted_indices]
total_values = [(R[i] - L[i] + 1) * V[i] for i in range(n)]
def compute_max_left_aligned(L, R, V, total_values):
max_sum = 0
ptr = 0
current_sum = 0
for i in range(n):
window_end = L[i] + k - 1
while ptr < n and R[ptr] <= window_end:
current_sum += total_values[ptr]
ptr += 1
candidate = current_sum
if ptr < n and L[ptr] <= window_end:
candidate += (window_end - L[ptr] + 1) * V[ptr]
if candidate > max_sum:
max_sum = candidate
if ptr > i:
current_sum -= total_values[i]
else:
ptr = i + 1
return max_sum
left_aligned_max = compute_max_left_aligned(L, R, V, total_values)
right_aligned_max = compute_max_left_aligned(
[-x for x in reversed(R)],
[-x for x in reversed(L)],
V[::-1],
total_values[::-1]
)
return max(left_aligned_max, right_aligned_max) % 1000000007