Find Sorted Submatrices With Maximum Element at Most K - Problem
๐ฏ Find Sorted Submatrices With Maximum Element at Most K
Imagine you're a data analyst working with a 2D grid of numbers, and you need to identify specific rectangular regions that meet strict criteria. Your task is to count how many submatrices satisfy two important conditions:
- ๐ข The maximum element in the submatrix is โค
k - ๐ Each row in the submatrix is sorted in non-increasing order (descending)
A submatrix is any rectangular region you can select from the grid by choosing coordinates (x1, y1) as the top-left corner and (x2, y2) as the bottom-right corner, where all cells grid[x][y] with x1 โค x โค x2 and y1 โค y โค y2 are included.
Example: For grid [[7,6,3],[7,6,3]] with k=6, the submatrix from (0,1) to (1,2) containing [[6,3],[6,3]] is valid because:
- Maximum element is 6 โค k
- Both rows [6,3] and [6,3] are in non-increasing order
Return the total count of all such valid submatrices.
Input & Output
example_1.py โ Basic Case
$
Input:
grid = [[7,6,3],[7,6,3]], k = 6
โบ
Output:
4
๐ก Note:
Valid submatrices: [[6]], [[3]], [[6,3]], and [[6,3],[6,3]]. All satisfy max โค k and non-increasing rows.
example_2.py โ Single Row
$
Input:
grid = [[7,6,3]], k = 3
โบ
Output:
2
๐ก Note:
Only [[3]] and [[6,3]] are valid. [7] and [7,6] have elements > k.
example_3.py โ No Valid Submatrices
$
Input:
grid = [[1,3,5],[2,4,6]], k = 2
โบ
Output:
3
๐ก Note:
Valid submatrices are [[1]], [[2]], and single cell submatrices with value โค 2. Rows are not properly sorted.
Constraints
- m == grid.length
- n == grid[i].length
- 1 โค m, n โค 1000
- 0 โค grid[i][j] โค 1000
- 0 โค k โค 1000
Visualization
Tap to expand
Understanding the Visualization
1
Setup Inspection
Examine rectangular sections of chocolate trays
2
Check Sweetness
Ensure no chocolate exceeds sweetness limit k
3
Verify Arrangement
Confirm each row goes from sweetest to least sweet
4
Count Valid Sections
Tally all sections meeting both criteria
Key Takeaway
๐ฏ Key Insight: By treating each row as a base for building histograms and using monotonic stacks, we efficiently count all valid rectangular regions without redundant checking.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code