#2736
Maximum Sum Queries
HardArrayBinary SearchStackBinary Indexed TreeSegment TreeSortingMonotonic StackSortingHeapTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + q log q) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n + q log q)Space O(n)
By sorting the input arrays and using a data structure to efficiently track valid sums, we can significantly reduce the number of comparisons needed for each query.
⚙️
Algorithm
5 steps- 1Step 1: Create a list of tuples (nums1[i], nums2[i]) and sort it by nums1[i] in descending order.
- 2Step 2: Create a list of queries with their original indices and sort them by x-coordinate in descending order.
- 3Step 3: Initialize a max-heap (or priority queue) to keep track of valid sums as we process each query.
- 4Step 4: For each query, while there are elements in the sorted tuples that meet the x condition, add their sums to the heap if they also meet the y condition.
- 5Step 5: For each query, the maximum sum can be retrieved from the heap; if empty, return -1.
solution.py16 lines
1import heapq
2
3def maxSumQueries(nums1, nums2, queries):
4 indexed_queries = sorted(enumerate(queries), key=lambda x: -x[1][0])
5 pairs = sorted(zip(nums1, nums2), key=lambda x: -x[0])
6 results = [-1] * len(queries)
7 max_heap = []
8 j = 0
9 for idx, (x, y) in indexed_queries:
10 while j < len(pairs) and pairs[j][0] >= x:
11 heapq.heappush(max_heap, pairs[j][0] + pairs[j][1])
12 j += 1
13 while max_heap and pairs[j-1][1] < y:
14 heapq.heappop(max_heap)
15 results[idx] = max_heap[0] if max_heap else -1
16 return resultsℹ
Complexity note: The time complexity is dominated by the sorting steps, which are O(n log n) for the pairs and O(q log q) for the queries. The space complexity is O(n) due to the storage of pairs.
- 1Sorting the input arrays allows us to efficiently manage the constraints of the queries.
- 2Using a max-heap helps in quickly retrieving the maximum sum that meets the conditions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.