Maximize Win From Two Segments - Problem
Imagine you're planning a treasure hunt along a straight path! ๐ดโโ ๏ธ
You have an array prizePositions that shows where prizes are located on the X-axis, sorted in non-decreasing order. Multiple prizes can exist at the same position. You're also given an integer k representing the length of segments you can choose.
Your mission: Select exactly two segments, each of length k, to maximize the number of prizes you can collect. You win any prize whose position falls within at least one of your chosen segments (including endpoints).
Key points:
- Each segment has length
kwith integer endpoints - The two segments can overlap - this might be optimal!
- A prize at position
pis won if it falls in segment[a, a+k]whena โค p โค a+k
Example: If k = 2, segments [1, 3] and [2, 4] would collect prizes at positions 1, 2, 3, and 4.
Input & Output
example_1.py โ Basic Case
$
Input:
prizePositions = [1,1,2,2,3,3,5], k = 2
โบ
Output:
7
๐ก Note:
Choose segments [1,3] and [1,3] (overlapping). The first segment covers prizes at positions 1,1,2,2,3,3 (6 prizes), and the second segment covers the same prizes. Since they overlap completely, we get all 7 prizes total (including the prize at position 5 is not optimal, so we choose segments [1,3] and [3,5] to get prizes at 1,1,2,2,3,3,5).
example_2.py โ Non-overlapping Optimal
$
Input:
prizePositions = [1,2,3,4,5,6,7,8,9,10], k = 2
โบ
Output:
6
๐ก Note:
Choose segments [1,3] and [8,10]. First segment covers positions 1,2,3 (3 prizes) and second segment covers positions 8,9,10 (3 prizes). Total = 6 prizes. This is better than overlapping segments.
example_3.py โ All Same Position
$
Input:
prizePositions = [1,1,1,1,1], k = 0
โบ
Output:
5
๐ก Note:
With k=0, each segment has length 0, so can only cover one position. Both segments cover position 1, getting all 5 prizes at that position.
Constraints
- 1 โค prizePositions.length โค 105
- 1 โค prizePositions[i] โค 109
- 0 โค k โค 109
- prizePositions is sorted in non-decreasing order
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Coast
You see treasures at positions [1,1,2,2,3,3,5] and have two nets of length k=2
2
Plan First Net
Calculate the best position for your first net at each location
3
Deploy Second Net
For each second net position, find the best first net that doesn't interfere
4
Maximize Treasure
Combine both nets optimally to collect maximum treasures
Key Takeaway
๐ฏ Key Insight: The optimal solution uses dynamic programming to precompute the best first segment ending at each position, then combines it with a sliding window approach to efficiently evaluate all possible second segment positions. This reduces time complexity from O(nยณ) to O(n)!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code