Problem solution · Python

Find Sorted Submatrices With Maximum Element at Most K

Find Sorted Submatrices With Maximum Element at Most K: a Python solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Dynamic programming
Source
walkccc LeetCode Solutions
Length
45 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

Dynamic programming

For Find Sorted Submatrices With Maximum Element at Most K, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 45 lines of Python from the credited upstream file 3359.py.
  • The implementation visibly relies on sequence storage, cached states.
  • No explicit loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

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 codeFind Sorted Submatrices With Maximum Element at Most K · PythonPython
Use this to learn the idea, then write your own version.
from dataclasses import dataclass  @dataclass(frozen=True)class T:  subarrayWidth: int  rowIndex: int  accumulatedSubmatrices: int  class Solution:  def countSubmatrices(self, grid: list[list[int]], k: int) -> int:    m = len(grid)    n = len(grid[0])    ans = 0    # dp[i][j] := the number of valid subarrays ending in grid[i][j]    dp = [[0] * n for _ in range(m)]    # stacks[j] := the stack of valid    # (subarray width, row index, number of accumulated submatrices) ending in    # column j    stacks: list[T] = [[T(0, -1, 0)] for _ in range(n)]     for i, row in enumerate(grid):      for j, num in enumerate(row):        if num > k:          stacks[j] = [T(0, i, 0)]        else:          dp[i][j] = 1          if j > 0 and row[j - 1] <= k and row[j - 1] >= row[j]:            # Extend the valid subarrays to the current number.            dp[i][j] += dp[i][j - 1]          width = dp[i][j]          # Remove subarray widths greater than the current count since they          # will become invalid.          while stacks[j] and width < stacks[j][-1].subarrayWidth:            stacks[j].pop()          height = i - stacks[j][-1].rowIndex          newSubmatrices = width * height          accumulatedSubmatrices = (stacks[j][-1].accumulatedSubmatrices +                                    newSubmatrices)          ans += accumulatedSubmatrices          stacks[j].append(T(width, i, accumulatedSubmatrices))     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 ↗