Problem solution · Python

Maximum Sum Queries

Maximum Sum Queries: a Python solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sliding window or two pointers
Source
walkccc LeetCode Solutions
Length
67 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Maximum Sum Queries, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMaximum Sum Queries · PythonPython
Use this to learn the idea, then write your own version.
from dataclasses import dataclass  @dataclass(frozen=True)class Pair:  x: int  y: int   def __iter__(self):    yield self.x    yield self.y  @dataclass(frozen=True)class IndexedQuery:  queryIndex: int  minX: int  minY: int   def __iter__(self):    yield self.queryIndex    yield self.minX    yield self.minY  class Solution:  def maximumSumQueries(      self,      nums1: list[int],      nums2: list[int],      queries: list[list[int]],  ) -> list[int]:    pairs = sorted([Pair(nums1[i], nums2[i])                   for i in range(len(nums1))], key=lambda x: x.x, reverse=True)    ans = [0] * len(queries)    stack = []  # [(y, x + y)]     pairsIndex = 0    for queryIndex, minX, minY in sorted([IndexedQuery(i, query[0], query[1])                                          for i, query in enumerate(queries)],                                         key=lambda x: -x.minX):      while pairsIndex < len(pairs) and pairs[pairsIndex].x >= minX:        # x + y is a better candidate. Given that x is decreasing, the        # condition "x + y >= stack[-1][1]" suggests that y is relatively        # larger, thereby making it a better candidate.        x, y = pairs[pairsIndex]        while stack and x + y >= stack[-1][1]:          stack.pop()        if not stack or y > stack[-1][0]:          stack.append((y, x + y))        pairsIndex += 1      j = self._firstGreaterEqual(stack, minY)      ans[queryIndex] = -1 if j == len(stack) else stack[j][1]     return ans   def _firstGreaterEqual(self, A: list[tuple[int, int]], target: int) -> int:    l = 0    r = len(A)    while l < r:      m = (l + r) // 2      if A[m][0] >= target:        r = m      else:        l = m + 1    return l 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗