3070. Count Submatrices with Top-Left Element and Sum Less Than k
EasyView on LeetCode
Time: O(mn)
Space: O(mn)
Problem Overview
Count elements greater than all neighbors.
Intuition
Count elements greater than all neighbors. For each element: if greater than left and right neighbors: count.
Algorithm
- 1For i from 1 to n-2: if nums[i] > nums[i-1] && nums[i] > nums[i+1]: count++.
Common Pitfalls
- •Endpoints are not counted (no two neighbors). Interior elements only.
3070.cs
C#
// Approach: 2D prefix sum from top-left; count cells where prefix sum ≤ k.
// Time: O(mn) Space: O(mn)
public class Solution
{
public int CountSubmatrices(int[][] grid, int k)
{
int m = grid.Length;
int n = grid[0].Length;
int ans = 0;
int[,] prefix = new int[m + 1, n + 1];
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
prefix[i + 1, j + 1] = grid[i][j] + prefix[i, j + 1] + prefix[i + 1, j] - prefix[i, j];
if (prefix[i + 1, j + 1] <= k)
++ans;
}
}
return ans;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)