Find Sorted Submatrices With Maximum Element at Most K - Problem
You are given a 2D matrix grid of size m x n. You are also given a non-negative integer k.
Return the number of submatrices of grid that satisfy the following conditions:
- The maximum element in the submatrix is less than or equal to k
- Each row in the submatrix is sorted in non-increasing order
A submatrix (x1, y1, x2, y2) is formed by choosing all cells grid[x][y] where x1 <= x <= x2 and y1 <= y <= y2.
Input & Output
Example 1 — Basic Case
$
Input:
grid = [[7,6,3],[2,1,0]], k = 2
›
Output:
6
💡 Note:
Valid submatrices: (1,0) contains [2], (1,1) contains [1], (1,2) contains [0], (1,0,1,1) contains [2,1], (1,1,1,2) contains [1,0], (1,0,1,2) contains [2,1,0]. All have max ≤ 2 and non-increasing rows.
Example 2 — Single Cell
$
Input:
grid = [[1,2,3],[4,5,6]], k = 2
›
Output:
1
💡 Note:
Only single cell with value ≤ 2 is valid: grid[0][0]=1. Multi-cell submatrices fail row sorting constraint since rows are increasing, not non-increasing.
Example 3 — All Valid
$
Input:
grid = [[2,1],[1,0]], k = 5
›
Output:
6
💡 Note:
All elements ≤ 5 and all rows non-increasing. Valid submatrices: 4 single cells + 2 row submatrices + entire 2×2 matrix = 6 total.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 100
- 0 ≤ grid[i][j] ≤ 100
- 0 ≤ k ≤ 100
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code