- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 60 lines of C++ from the credited upstream file 2736.cpp.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct Pair {2 int x;3 int y;4};5 6struct IndexedQuery {7 int queryIndex;8 int minX;9 int minY;10};11 12class Solution {13 public:14 vector<int> maximumSumQueries(vector<int>& nums1, vector<int>& nums2,15 vector<vector<int>>& queries) {16 const vector<Pair> pairs = getPairs(nums1, nums2);17 vector<int> ans(queries.size());18 vector<pair<int, int>> stack; 19 20 int pairsIndex = 0;21 for (const auto& [queryIndex, minX, minY] : getIndexedQueries(queries)) {22 while (pairsIndex < pairs.size() && pairs[pairsIndex].x >= minX) {23 const auto [x, y] = pairs[pairsIndex++];24 25 26 27 while (!stack.empty() && x + y >= stack.back().second)28 stack.pop_back();29 if (stack.empty() || y > stack.back().first)30 stack.emplace_back(y, x + y);31 }32 const auto it = ranges::lower_bound(stack, pair<int, int>{minY, INT_MIN});33 ans[queryIndex] = it == stack.end() ? -1 : it->second;34 }35 36 return ans;37 }38 39 private:40 vector<Pair> getPairs(const vector<int>& nums1, const vector<int>& nums2) {41 vector<Pair> pairs;42 for (int i = 0; i < nums1.size(); ++i)43 pairs.push_back({nums1[i], nums2[i]});44 ranges::sort(pairs, ranges::greater{},45 [](const Pair& pair) { return pair.x; });46 return pairs;47 }48 49 vector<IndexedQuery> getIndexedQueries(const vector<vector<int>>& queries) {50 vector<IndexedQuery> indexedQueries;51 for (int i = 0; i < queries.size(); ++i)52 indexedQueries.push_back({i, queries[i][0], queries[i][1]});53 ranges::sort(indexedQueries,54 [](const IndexedQuery& a, const IndexedQuery& b) {55 return a.minX > b.minX;56 });57 return indexedQueries;58 }59};60