Problem Description
Given a sorted array prizePositions representing positions on the X-axis where prizes are located (there may be duplicates), and an integer k, you may select two segments of length k (with integer endpoints). Each segment covers prizes with positions between its endpoints (inclusive). The two segments can overlap. The goal is to maximize the total number of prizes captured by the two segments.
Key Insights
- Because prizePositions is sorted, a two-pointer (sliding window) approach can efficiently calculate how many prizes fall inside a segment covering [x, x+k].
- Precompute for each index the number of prizes that can be captured starting at that position by moving the right pointer until the prize position exceeds prizePositions[i] + k.
- Build an auxiliary suffix array to keep track of the maximum count for segments starting at or after any given index.
- For each segment represented by a starting index, combine its count with the best count from a segment starting after its interval ends.
- Binary Search can also be used to find the ending index of each segment, but the sliding window method is direct and efficient.
Space and Time Complexity
Time Complexity: O(n) – two pointers traverse the prizePositions array linearly and the suffix array is built in O(n).
Space Complexity: O(n) – extra arrays are used to store counts for each window and the suffix maximum counts.
Solution
We first use a sliding window to compute the number of prizes that can be captured by a segment starting at each prizePositions[i] (i.e. covering [prizePositions[i], prizePositions[i]+k]). This gives us a count array. As we determine the window for prizePositions[i], we also compute the index where the window ends.
Next, we build a suffix array such that for any index i, suf[i] represents the maximum count of any segment starting from index i to the end of prizePositions.
Finally, for each starting segment, we combine its count with the best possible count from a segment that does not interfere (i.e. where the left endpoint is outside the current segment’s range). The final answer is the maximum sum found among all such pairs, ensuring we consider cases where one segment might cover all the prizes.