Find a Maximum-Sum Window in a Sparse Array
AmazonSoftware Engineer · Online AssessmentLast updated
This problem tests the ability to optimize sliding window calculations for extremely large arrays by leveraging compressed data structures (run-length encoding) rather than materializing the full array.
Problem Statement
You are given a sparse array represented as a list of segments, where each segment is defined by a (value, length) tuple. For example, [(10, 3), (5, 2)] represents the array [10, 10, 10, 5, 5].
Given this compressed representation and an integer k, find the maximum sum of any contiguous subarray of length k. The total length of the original array can be up to 10^15, but the number of segments will not exceed 10^5.
Function Signature
def max_window_sum(segments, k):
# segments: List of tuples (value, length)
# k: int
pass
Constraints
- Total array length
N<=10^15 - Number of segments
M<=10^5 1 <= k <= N
Examples
Example 1:
Input: segments = [(1, 2), (3, 4), (2, 1)], k = 3
Array representation: [1, 1, 3, 3, 3, 3, 2]
Windows of length 3: [1,1,3]=5, [1,3,3]=7, [3,3,3]=9, [3,3,3]=9, [3,3,2]=8
Output: 9
Example 2:
Input: segments = [(10, 100), (20, 100)], k = 150
Output: 2500 (50 elements of 10 + 100 elements of 20)
Edge Cases
kis equal to the length of a single segment.kspans multiple segments.- All values in the segments are negative.
Hints
Hint 1
Instead of expanding the array, maintain a pointer for the start and end of the window in terms of segment indices.
Hint 2
Use a sliding window approach: when moving the window forward, subtract the element exiting on the left and add the element entering on the right by calculating their values based on the current segment.
Hint 3
Since segments have varying lengths, maintain the current 'state' of the window (how many elements of the current segment are currently included) to efficiently update the total sum in O(1) or O(M) time.
Follow-up questions
- How would you modify your solution if we needed to return the starting index of the maximum sum window?
- If the array were not compressed and we were given `M` updates that change the value of specific ranges, how would the complexity change?
- Can you solve this if `k` is not fixed, but instead you need the maximum sum of any window of length *at most* `k`?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.