Find a Maximum-Sum Window in a Sparse Array
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Take-home Project
# Find a Maximum-Sum Window in a Sparse Array
An integer array is represented by constant-value segments instead of individual elements. Each segment `[start, end, value]` means that every index from `start` through `end`, inclusive, contains `value`. Every index not covered by a segment contains zero.
Return the maximum sum of any contiguous subarray of exactly `window_size` elements without expanding the full array.
### Function Signature
```python
def max_sparse_window_sum(
array_length: int,
segments: list[list[int]],
window_size: int,
) -> int:
...
```
### Example
```text
Input: array_length = 8
segments = [[1, 3, 4], [6, 7, 1]]
window_size = 3
Conceptual array: [0, 4, 4, 4, 0, 0, 1, 1]
Output: 12
```
### Constraints
- `1 <= array_length <= 10^18`
- `1 <= window_size <= array_length`
- `0 <= len(segments) <= 200_000`
- Each segment has three integers `[start, end, value]`.
- `0 <= start <= end < array_length`
- Segments do not overlap, but they may be unsorted and adjacent.
- `-10^9 <= value <= 10^9`
### Clarifications
- Array indices are zero-based.
- A segment's endpoints are inclusive.
- Uncovered indices contribute zero.
- The returned sum may be negative only when every legal window has a negative total.
- Do not allocate memory proportional to `array_length` or `window_size`.
- Do not mutate `segments`.
- Defining `array_length` explicitly is a practice assumption that makes the sparse array's finite domain unambiguous.
### Hints
- A window's sum changes only when one of its boundaries crosses a segment boundary.
- Consider a sweep over compressed breakpoints or an interval-prefix representation.
- Be careful about long zero gaps and windows whose boundaries fall inside segments.
Quick Answer: Find the maximum sum of any fixed-length window in an enormous sparse array represented by nonoverlapping constant-value segments. Sweep compressed breakpoints or use interval prefixes so runtime and memory depend on the segments rather than the full array length.
Return the maximum sum of an exact-size contiguous window over a finite array represented by nonoverlapping constant-value segments, without expanding the array.
Constraints
- 1 <= window_size <= array_length <= 10^18
- At most 200000 nonoverlapping segments
- Uncovered indices have value zero
Examples
Input: {'array_length': 8, 'segments': [[1, 3, 4], [6, 7, 1]], 'window_size': 3}
Expected Output: 12
Explanation: The best window covers the three values of four.
Input: {'array_length': 5, 'segments': [], 'window_size': 2}
Expected Output: 0
Explanation: An entirely uncovered array is all zeros.
Hints
- Build a prefix-sum query over sorted sparse segments.
- The window sum changes slope only when either boundary crosses a segment boundary.