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.

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

Visualization

Tap to expand
Maximum Sum Queries INPUT nums1: 4 3 1 nums2: 2 4 9 i=0 i=1 i=2 Sums: 6 7 10 Queries: [4,1] [1,3] [2,5] Pairs: (4,2), (3,4), (1,9) Find max sum where nums1[j]>=x, nums2[j]>=y ALGORITHM STEPS 1 Create Pairs Combine nums1, nums2, sum 2 Sort by nums1 (desc) Also sort queries by x 3 Use Segment Tree Track max sum by nums2 4 Process Queries Add valid pairs, query max Query [4,1]: Only (4,2) valid: sum=6 Query [1,3]: (3,4) and (1,9) valid max(7,10) = 10 Query [2,5]: No pair satisfies both conditions: -1 FINAL RESULT Output Array [6, 10, -1] Breakdown: Query [4,1] --> 6 idx 0: 4>=4, 2>=1 [OK] sum = 4+2 = 6 Query [1,3] --> 10 idx 1: 3>=1, 4>=3 sum=7 idx 2: 1>=1, 9>=3 sum=10 Query [2,5] --> -1 No valid index found Key Insight: Sort pairs by nums1 descending and process queries in same order. Use a segment tree indexed by nums2 values to track maximum sums. For each query, add all pairs with nums1 >= x, then query segment tree for max sum where nums2 >= y. Time: O((n+q) log n) | Space: O(n) TutorialsPoint - Maximum Sum Queries | Optimal Solution with Segment Tree
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