Count Submatrices with Top-Left Element and Sum Less Than k

You are given a 0-indexed integer matrix grid and an integer k.

Return the number of submatrices that contain the top-left element of the grid, and have a sum less than or equal to k.

Example 1
7 6 3
6 6 1
Inputgrid = [[7,6,3],[6,6,1]], k = 18
Output4
There are only 4 submatrices that contain the top-left element of grid and have a sum less than or equal to 18.
Example 2
7 2 9
1 5 0
2 6 6
Inputgrid = [[7,2,9],[1,5,0],[2,6,6]], k = 20
Output6
There are only 6 submatrices that contain the top-left element of grid and have a sum less than or equal to 20.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= n, m <= 1000
  • 0 <= grid[i][j] <= 1000
  • 1 <= k <= 10^9

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate