Problem Description
Given two 0-indexed integer arrays nums1 and nums2 (both of length n) and a 1-indexed 2D array queries, where each query is represented as [x, y], the goal is to find for each query the maximum value of nums1[j] + nums2[j] among all indices j (0 <= j < n) satisfying nums1[j] >= x and nums2[j] >= y. If no such index exists, return -1 for that query.
Key Insights
- Process queries offline by sorting them according to the first condition (x) in descending order.
- Similarly, sort the array entries (points) by their nums1 values (also descending) so that when processing a query you can quickly pick all candidate indices.
- Use coordinate compression on nums2 to make it feasible to build an efficient data structure.
- A Fenwick Tree (Binary Indexed Tree) or Segment Tree is employed to maintain and query the maximum sum for points that satisfy the second condition (nums2 >= y).
- Each query then uses a range query on the data structure to decide the result.
Space and Time Complexity
Time Complexity: O((n + q) log n), where n = length of nums arrays and q = number of queries.
Space Complexity: O(n) to store the BIT/Segment Tree plus extra space for sorting/coordinate compression.
Solution
The solution works by processing both the data points and the queries in descending order by their nums1 or query x value. For each query [x, y]:
- Add all points with nums1 >= x into a data structure keyed by their compressed nums2 value. Each point holds its sum = nums1 + nums2.
- Use the data structure (BIT or Segment Tree) to query the maximum sum for indices whose corresponding nums2 values (after compression) are >= y.
- Record the result, or -1 if the query yields no valid point. Coordinate compression is used for nums2 values to build a BIT/Segment Tree efficiently, ensuring updates and queries in O(log n).