Problem solution · Python

Maximum Number of Points From Grid Queries

Maximum Number of Points From Grid Queries: a Python solution using heap or priority queue. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Heap or priority queue
Source
walkccc LeetCode Solutions
Length
47 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

Heap or priority queue

For Maximum Number of Points From Grid Queries, the implementation repeatedly takes the currently best candidate from a heap while inserting newly available choices.

  1. Define the priority key and whether the smallest or largest item should lead.
  2. Push each candidate when it becomes eligible.
  3. 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.

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 Number of Points From Grid Queries · PythonPython
Use this to learn the idea, then write your own version.
from dataclasses import dataclass  @dataclass(frozen=True)class IndexedQuery:  queryIndex: int  query: int   def __iter__(self):    yield self.queryIndex    yield self.query  class Solution:  def maxPoints(self, grid: list[list[int]], queries: list[int]) -> list[int]:    DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))    m = len(grid)    n = len(grid[0])    ans = [0] * len(queries)    minHeap = [(grid[0][0], 0, 0)]  # (grid[i][j], i, j)    seen = {(0, 0)}    accumulate = 0     for queryIndex, query in sorted([IndexedQuery(i, query)                                     for i, query in enumerate(queries)],                                    key=lambda x: x.query):      while minHeap:        val, i, j = heapq.heappop(minHeap)        if val >= query:          # The smallest neighbor is still larger than `query`, so no need to          # keep exploring. Re-push (i, j, grid[i][j]) back to the `minHeap`.          heapq.heappush(minHeap, (val, i, j))          break        accumulate += 1        for dx, dy in DIRS:          x = i + dx          y = j + dy          if x < 0 or x == m or y < 0 or y == n:            continue          if (x, y) in seen:            continue          heapq.heappush(minHeap, (grid[x][y], x, y))          seen.add((x, y))      ans[queryIndex] = accumulate     return ans 

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 ↗