[LeetCode] Maximize Win From Two Segments

2555. Maximize Win From Two Segments

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int maximizeWin(vector<int>& prizePositions, int k) {
unordered_map<int, int> freq, cnt;
for(auto p : prizePositions) freq[p] += 1;
int ma = 0, res = 0, now = 0, l = prizePositions.size() - 1, r = l;
while(l >= 0) {
while(l > 0 and prizePositions[l] == prizePositions[l-1]) l -= 1;
now += freq[prizePositions[l]];
while(prizePositions[l] + k < prizePositions[r]) {
while(r > 0 and prizePositions[r] == prizePositions[r-1]) r -= 1;
now -= freq[prizePositions[r]];
ma = max(ma, cnt[prizePositions[r]]);
r -= 1;
}
cnt[prizePositions[l]] = now;
res = max(res, now + ma);
l -= 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/07/PS/LeetCode/maximize-win-from-two-segments/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.