Maximum Sum Queries - Problem
Maximum Sum Queries
You're given two arrays
The Challenge: For each query
If no such index exists, return
Example: If
You're given two arrays
nums1 and nums2 of equal length, and a collection of queries. Each query asks: "What's the maximum sum of nums1[j] + nums2[j] where nums1[j] is at least x and nums2[j] is at least y?"The Challenge: For each query
[x, y], find an index j where both conditions are met: nums1[j] >= x AND nums2[j] >= y. Among all valid indices, return the one with the maximum sum nums1[j] + nums2[j].If no such index exists, return
-1 for that query.Example: If
nums1 = [4,3,1], nums2 = [2,4,9], and query is [4,1], only index 0 satisfies both conditions (4>=4 and 2>=1), so return 4+2=6. Input & Output
example_1.py โ Basic Case
$
Input:
nums1 = [4,3,1], nums2 = [2,4,9], queries = [[4,1],[1,3],[2,5]]
โบ
Output:
[6,10,-1]
๐ก Note:
Query [4,1]: Only index 0 satisfies (4>=4 and 2>=1), sum = 4+2 = 6. Query [1,3]: Indices 1,2 satisfy conditions, max sum is 1+9 = 10 at index 2. Query [2,5]: No index satisfies both conditions, return -1.
example_2.py โ All Valid
$
Input:
nums1 = [3,2,5], nums2 = [2,3,4], queries = [[1,1]]
โบ
Output:
[9]
๐ก Note:
All indices satisfy nums1[j]>=1 and nums2[j]>=1. Index 2 gives maximum sum: 5+4=9.
example_3.py โ No Valid Points
$
Input:
nums1 = [1,2,3], nums2 = [4,3,2], queries = [[4,4]]
โบ
Output:
[-1]
๐ก Note:
No index satisfies both nums1[j]>=4 and nums2[j]>=4, so return -1.
Visualization
Tap to expand
Understanding the Visualization
1
Plot Points
Each index becomes a point (nums1[i], nums2[i]) with value nums1[i] + nums2[i]
2
Sort by X-coordinate
Sort all points by nums1 values to handle one dimension efficiently
3
Eliminate Dominated Points
Use monotonic stack to keep only points that could be optimal for some query
4
Answer Queries
For each query rectangle, find the best point among candidates
Key Takeaway
๐ฏ Key Insight: By sorting one dimension and using a monotonic stack for the other, we eliminate all dominated points and can efficiently answer range maximum queries in 2D space.
Time & Space Complexity
Time Complexity
O(n ร m)
For each of m queries, we check all n indices
โ Linear Growth
Space Complexity
O(1)
Only using a few variables, no additional data structures
โ Linear Space
Constraints
- 1 โค nums1.length, nums2.length โค 105
- 1 โค nums1[i], nums2[i] โค 109
- 1 โค queries.length โค 105
- queries[i].length == 2
- 1 โค xi, yi โค 109
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code