Maximize Win From Two Segments Problem
Description
LeetCode Problem 2555.
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 i^th 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 satisfies1 <= prizePositions[i] <= 3or2 <= prizePositions[i] <= 4.
Return the maximum number of prizes you can win if you choose the two segments optimally.
Example 1:
Input: prizePositions = [1,1,2,2,3,3,5], k = 2
Output: 7
Explanation: In this example, you can win all 7 prizes by selecting two segments [1, 3] and [3, 5].
Example 2:
Input: prizePositions = [1,2,3,4], k = 0
Output: 2
Explanation: For this example, one choice for the segments is [3, 3] and [4, 4], and you will be able to get 2 prizes.
Constraints:
1 <= prizePositions.length <= 10^51 <= prizePositions[i] <= 10^90 <= k <= 10^9prizePositionsis sorted in non-decreasing order.
Solution
Approach: DP with Binary Search
Let f[i] be the most prizes one segment of length k can cover among the first i prizes (the positions are sorted). Process the prizes in order. For the i-th prize at position x, binary search the first index j with prizePositions[j] >= x - k: the segment ending at x covers i - j prizes.
Use it as the second segment on top of the best first segment lying entirely before it, giving f[j] + i - j, and keep the maximum as the answer. Then update f[i] = max(f[i - 1], i - j).
Complexity: O(n log n) time and O(n) extra space.
from bisect import bisect_left
class Solution:
def maximizeWin(self, prizePositions: List[int], k: int) -> int:
n = len(prizePositions)
f = [0] * (n + 1)
ans = 0
for i, x in enumerate(prizePositions, 1):
j = bisect_left(prizePositions, x - k)
ans = max(ans, f[j] + i - j)
f[i] = max(f[i - 1], i - j)
return ans