Input: grid =[[4,3,2,1],[8,7,6,1]], k =3Output: 8Explanation:
****
The 8 submatrices are:*`[[1]]`*`[[1]]`*`[[2,1]]`*`[[3,2,1]]`*`[[1],[1]]`*`[[2]]`*`[[3]]`*`[[3,2]]`
Example 2:
1
2
3
4
5
Input: grid =[[1,1,1],[1,1,1],[1,1,1]], k =1Output: 36Explanation:
There are 36 submatrices of grid. All submatrices have their maximum element
equal to 1.
For each row, we can use a histogram to represent the number of consecutive rows above (including the current) where each column’s value is at most k and the row is non-increasing. Then, for each row, we count the number of rectangles (submatrices) ending at that row using a monotonic stack, similar to the largest rectangle in histogram problem.
classSolution {
funcountSortedSubmatrices(grid: Array<IntArray>, k: Int): Int {
val m = grid.size
val n = grid[0].size
var ans = 0val height = IntArray(n)
for (i in0 until m) {
for (j in0 until n) {
if (grid[i][j] <= k && (j ==0|| grid[i][j] <= grid[i][j-1]))
height[j]++else height[j] = 0 }
val stk = ArrayDeque<Int>()
val left = IntArray(n)
for (j in0 until n) {
while (stk.isNotEmpty() && height[stk.last()] >= height[j]) stk.removeLast()
left[j] = j - (if (stk.isEmpty()) -1else stk.last())
stk.addLast(j)
}
for (j in0 until n) ans += height[j] * left[j]
}
return ans
}
}
classSolution:
defcountSortedSubmatrices(self, grid: list[list[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
ans =0 height = [0] * n
for i in range(m):
for j in range(n):
if grid[i][j] <= k and (j ==0or grid[i][j] <= grid[i][j-1]):
height[j] +=1else:
height[j] =0 stk = []
left = [0] * n
for j in range(n):
while stk and height[stk[-1]] >= height[j]:
stk.pop()
left[j] = j - (stk[-1] if stk else-1)
stk.append(j)
for j in range(n):
ans += height[j] * left[j]
return ans