[LeetCode] Two Best Non-Overlapping Events

2054. Two Best Non-Overlapping Events

You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and if you attend this event, you will receive a value of valuei. You can choose at most two non-overlapping events to attend such that the sum of their values is maximized.

Return this maximum sum.

Note that the start time and end time is inclusive: that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t, the next event must start at or after t + 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int maxTwoEvents(vector<vector<int>>& A) {
int res = INT_MIN;
unordered_map<int, int> mp;
for(auto& a : A) {
mp[a[0]] = max(mp[a[0]], a[2]);
res = max(res, a[2]);
}
vector<pair<int, int>> B;
for(auto& [k, v]: mp) {
B.push_back({k,v});
}
sort(begin(B), end(B));
for(int i = B.size()-1, ma = INT_MIN; i >= 0; i--) {
B[i].second = ma = max(ma, B[i].second);
}
for(int i = 0; i < A.size(); i++) {
int time = A[i][1], v = A[i][2];
auto lb = lower_bound(begin(B), end(B), pair<int,int>(time + 1, INT_MIN));
if(lb != end(B)) {
auto p = lb - begin(B);
res = max(res, v + B[p].second);
}
}


return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/10/PS/LeetCode/two-best-non-overlapping-events/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.