- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 47 lines of Python from the credited upstream file 2503.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
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 IndexedQuery:6 queryIndex: int7 query: int8 9 def __iter__(self):10 yield self.queryIndex11 yield self.query12 13 14class Solution:15 def maxPoints(self, grid: list[list[int]], queries: list[int]) -> list[int]:16 DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))17 m = len(grid)18 n = len(grid[0])19 ans = [0] * len(queries)20 minHeap = [(grid[0][0], 0, 0)] 21 seen = {(0, 0)}22 accumulate = 023 24 for queryIndex, query in sorted([IndexedQuery(i, query)25 for i, query in enumerate(queries)],26 key=lambda x: x.query):27 while minHeap:28 val, i, j = heapq.heappop(minHeap)29 if val >= query:30 31 32 heapq.heappush(minHeap, (val, i, j))33 break34 accumulate += 135 for dx, dy in DIRS:36 x = i + dx37 y = j + dy38 if x < 0 or x == m or y < 0 or y == n:39 continue40 if (x, y) in seen:41 continue42 heapq.heappush(minHeap, (grid[x][y], x, y))43 seen.add((x, y))44 ans[queryIndex] = accumulate45 46 return ans47