Maximize Win From Two Segments - Problem

There are some prizes on the X-axis. You are given an integer array prizePositions that is sorted in non-decreasing order, where prizePositions[i] is the position of the ith prize. There could be different prizes at the same position on the line.

You are also given an integer k.

You are allowed to select two segments with integer endpoints. The length of each segment must be k. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments).

The two selected segments may intersect.

For example if k = 2, you can choose segments [1, 3] and [2, 4], and you will win any prize i that satisfies 1 <= prizePositions[i] <= 3 or 2 <= prizePositions[i] <= 4.

Return the maximum number of prizes you can win if you choose the two segments optimally.

Input & Output

Example 1 — Basic Case
$ Input: prizePositions = [1,1,2,2,3,3,5], k = 2
Output: 6
💡 Note: Choose segments [1,3] and [3,5]. Segment [1,3] covers prizes at positions 1,1,2,2,3,3 (6 prizes total). Segment [3,5] covers prizes at positions 3,3,5 (3 prizes). Union covers 6 unique prizes.
Example 2 — Non-overlapping Optimal
$ Input: prizePositions = [1,2,3,4], k = 1
Output: 4
💡 Note: Choose segments [1,2] and [3,4]. First segment covers positions 1,2 (2 prizes), second segment covers positions 3,4 (2 prizes). Total: 4 prizes.
Example 3 — Single Position Multiple Prizes
$ Input: prizePositions = [1,1,1,1], k = 0
Output: 4
💡 Note: Both segments can cover position [1,1], capturing all 4 prizes at position 1.

Constraints

  • 1 ≤ prizePositions.length ≤ 105
  • 1 ≤ prizePositions[i] ≤ 109
  • 0 ≤ k ≤ 109
  • prizePositions is sorted in non-decreasing order

Visualization

Tap to expand
Maximize Win From Two SegmentsInput: prizePositions = [1,1,2,2,3,3,5], k = 21122335Prize positions on X-axisSegment 1: [1,3] covers 6 prizesSegment 2: [3,5] covers 0 new prizesUnion of both segments = 6 prizes totalOutput: 6
Understanding the Visualization
1
Input
Prize positions [1,1,2,2,3,3,5] with segment length k=2
2
Process
Find optimal placement of two segments of length k
3
Output
Maximum 6 prizes can be captured
Key Takeaway
🎯 Key Insight: Pre-compute optimal segments and use efficient boundary detection to maximize prize coverage
Asked in
Google 25 Amazon 18 Microsoft 15
23.0K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen