Peak Subarray Sum in a Run-Length-Encoded Sequence
Arrays & HashingAuto-graded · 20 test casesLast updated
Tests whether a candidate can find the maximum sum of a fixed-length window over a run-length-encoded array too large to expand in memory.
Problem Statement
A very long sequence of integers is stored in compressed form as a list of runs. Each run is a pair [value, length], meaning the value value repeats consecutively for length positions. For instance, [[4, 2], [7, 3]] encodes the sequence [4, 4, 7, 7, 7].
The total number of elements can reach 10^15, so the full sequence must never be materialized. Given the compressed representation and a window size k, return the largest sum achievable by any contiguous block of exactly k elements in the underlying sequence.
How the window sum changes
Think about sliding the window one step to the right. The new sum equals the old sum plus the element entering on the right minus the element leaving on the left. That difference stays constant for as long as neither edge of the window crosses a run boundary. Between two consecutive boundary events the window sum is a linear function of the start position, so its maximum on that stretch must occur at one of the two endpoints.
This means you only need to evaluate the window sum at a small set of candidate start positions:
- Position
0and positionN − k(the first and last valid starts). - Every position where a run boundary aligns with the left edge of the window.
- Every position
b − kwhere a run boundarybaligns with the right edge of the window.
All positions outside [0, N − k] are ignored. The total number of candidates is at most 2M + 4, where M is the number of runs.
Evaluating the sum at a candidate
Precompute two parallel arrays:
starts[i]— the index of the first element in runi.prefix_at_start[i]— the total sum of all elements before runi.
Given a position x, binary-search for the run that contains it, then compute:
P(x) = prefix_at_start[i] + value_i * (x - starts[i])
The window sum starting at position s is then P(s + k) − P(s).
Constraints
- Total sequence length
Nsatisfies1 ≤ N ≤ 10^15. - Number of runs
Msatisfies1 ≤ M ≤ 10^5. - Each run length is a positive integer.
1 ≤ k ≤ N.- Run values may be negative, zero, or positive.
- Do not materialize the full sequence; solutions that allocate
O(N)memory will exceed limits.
Examples
Example 1
Input: max_window_sum([[1, 2], [3, 4], [2, 1]], 3)
Output: 9
Example 2
Input: max_window_sum([[10, 100], [20, 100]], 150)
Output: 2500
Hints
Hint 1
The full sequence is too large to expand. Instead, think about how the window sum changes as you slide it one step at a time — when does that per-step change actually change?
Hint 2
The per-step change is constant between run boundaries at both the left and right edges of the window. That makes the sum a piecewise-linear function of the start position, and a linear function achieves its max at an endpoint — so you only need to check boundary-aligned positions.
Hint 3
Build a prefix-sum function using binary search on precomputed run-start offsets. Then collect all candidate start positions (run boundaries and those shifted left by k), filter to [0, N−k], and evaluate the window sum at each one.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why iterating element by element won't work
The total sequence length can reach 10^15. Even storing one integer per element is impossible, so any solution that expands the runs or slides the window one step at a time is out.
The piecewise-linearity insight
Define f(s) as the sum of the window starting at position s:
f(s) = P(s + k) − P(s)
where P(x) is the prefix sum of the first x elements. Inside a single run, P grows at a constant rate (the run's value), so P is piecewise linear with breakpoints at run boundaries.
Moving the window one step right changes the sum by A[s+k] − A[s]. That quantity stays constant as long as neither edge crosses a run boundary. So f is linear between consecutive boundary events, and a linear function on a closed interval takes its maximum at one of the two endpoints.
Candidate positions
The boundary events happen at:
- Every run start
b(left-edge event) — candidatesbfor start positions. - Every
b − k(right-edge event) — the start position where the right edge lands at boundaryb.
Together with the endpoints 0 and N − k, this gives at most 2M + 4 candidates. Any optimal start lies at or between two consecutive candidates, but because f is linear on that gap, the optimum must be at one of them. Checking only candidates is therefore exact.
Fast prefix-sum evaluation
Precompute:
starts[i]: cumulative length before runi.prefix_at_start[i]: cumulative element sum before runi.
For position x, binary-search for the last run starting at or before x, then:
P(x) = prefix_at_start[i] + value_i * (x − starts[i])
This is O(log M) per query.
Edge cases
- All negative values:
beststarts asNoneand is set on the first candidate, so the maximum is never artificially floored at zero. k == N:limit = 0, the only candidate is0, and the answer is the total sum.- Single run: every window has the same sum; any candidate returns it.
kspans many runs:P(s+k) − P(s)handles this in two binary searches with no per-run loop.
Complexity
- Time:
O(M log M)— building the precomputed arrays isO(M); there areO(M)candidates and each needs twoO(log M)binary searches. - Space:
O(M)for the precomputed arrays and candidate set.
Python's arbitrary-precision integers handle sums that can reach 10^15 × |value| without overflow.
Reference solution
from bisect import bisect_right
from typing import List
def max_window_sum(segments: List[List[int]], k: int) -> int:
# Precompute per-run starting positions and prefix sums before each run.
starts = []
prefix_at_start = []
boundaries = []
total_length = 0
total_sum = 0
for value, length in segments:
starts.append(total_length)
prefix_at_start.append(total_sum)
boundaries.append(total_length)
total_length += length
total_sum += value * length
# Sentinel: one past the last element (the "end" boundary).
boundaries.append(total_length)
# Valid start positions lie in [0, limit].
limit = total_length - k
def prefix_sum(position: int) -> int:
"""Sum of the first `position` elements."""
i = bisect_right(starts, position) - 1
return prefix_at_start[i] + segments[i][0] * (position - starts[i])
# Collect candidate start positions: endpoints plus every run boundary
# placed at the left edge or right edge of the window.
candidates = {0, limit}
for boundary in boundaries:
if 0 <= boundary <= limit:
candidates.add(boundary)
shifted = boundary - k
if 0 <= shifted <= limit:
candidates.add(shifted)
best = None
for start in candidates:
current = prefix_sum(start + k) - prefix_sum(start)
if best is None or current > best:
best = current
return best