Maximum Sum Queries

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
2D Point Domination Visualizationnums1[i] โ†’nums2[i] โ†‘P1(4,2) sum=6P2(3,4) sum=7P3(1,9) sum=10Query [4,1]xโ‰ฅ4, yโ‰ฅ1โœ“ Valid: sum=6Monotonic StackTop: (9,10) โ† Best for small xMid: (4,7) โ† BalancedBot: (2,6) โ† Best for large xDominated points removed!
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

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables, no additional data structures

n
2n
โœ“ 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
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
23.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen