- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 67 lines of Python from the credited upstream file 2736.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from dataclasses import dataclass2 3 4@dataclass(frozen=True)5class Pair:6 x: int7 y: int8 9 def __iter__(self):10 yield self.x11 yield self.y12 13 14@dataclass(frozen=True)15class IndexedQuery:16 queryIndex: int17 minX: int18 minY: int19 20 def __iter__(self):21 yield self.queryIndex22 yield self.minX23 yield self.minY24 25 26class Solution:27 def maximumSumQueries(28 self,29 nums1: list[int],30 nums2: list[int],31 queries: list[list[int]],32 ) -> list[int]:33 pairs = sorted([Pair(nums1[i], nums2[i])34 for i in range(len(nums1))], key=lambda x: x.x, reverse=True)35 ans = [0] * len(queries)36 stack = [] 37 38 pairsIndex = 039 for queryIndex, minX, minY in sorted([IndexedQuery(i, query[0], query[1])40 for i, query in enumerate(queries)],41 key=lambda x: -x.minX):42 while pairsIndex < len(pairs) and pairs[pairsIndex].x >= minX:43 44 45 46 x, y = pairs[pairsIndex]47 while stack and x + y >= stack[-1][1]:48 stack.pop()49 if not stack or y > stack[-1][0]:50 stack.append((y, x + y))51 pairsIndex += 152 j = self._firstGreaterEqual(stack, minY)53 ans[queryIndex] = -1 if j == len(stack) else stack[j][1]54 55 return ans56 57 def _firstGreaterEqual(self, A: list[tuple[int, int]], target: int) -> int:58 l = 059 r = len(A)60 while l < r:61 m = (l + r) 262 if A[m][0] >= target:63 r = m64 else:65 l = m + 166 return l67