forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-sum-queries.cpp
35 lines (34 loc) · 1.33 KB
/
maximum-sum-queries.cpp
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
31
32
33
34
35
// Time: O(nlogn + mlogm + mlogn)
// Space: O(n + m)
// sort, mono stack, binary search
class Solution {
public:
vector<int> maximumSumQueries(vector<int>& nums1, vector<int>& nums2, vector<vector<int>>& queries) {
vector<pair<int, int>> pairs;
for (int i = 0; i < size(nums1); ++i) {
pairs.emplace_back(nums1[i], nums2[i]);
}
sort(begin(pairs), end(pairs));
vector<tuple<int, int, int>> sorted_queries;
for (int i = 0; i < size(queries); ++i) {
sorted_queries.emplace_back(queries[i][0], queries[i][1], i);
}
sort(rbegin(sorted_queries), rend(sorted_queries));
vector<int> result(size(queries));
vector<pair<int, int>> stk;
for (const auto& [x, y, i] : sorted_queries) {
while (!empty(pairs) && pairs.back().first >= x) {
const auto [a, b] = pairs.back(); pairs.pop_back();
while (!empty(stk) && stk.back().second <= a + b) {
stk.pop_back();
}
if (empty(stk) || stk.back().first < b) {
stk.emplace_back(b, a + b);
}
}
const auto it = lower_bound(cbegin(stk), cend(stk), pair(y, 0));
result[i] = it != cend(stk) ? it->second : -1;
}
return result;
}
};