LeetCode-in-Java

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

Medium

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:

Input: grid = [[7,6,3],[6,6,1]], k = 18

Output: 4

Explanation: There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.

Example 2:

Input: grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20

Output: 6

Explanation: There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20.

Constraints:

Solution

public class Solution {
    public int countSubmatrices(int[][] grid, int k) {
        int n = grid[0].length;
        int[] sums = new int[n];
        int ans = 0;
        for (int[] ints : grid) {
            int sum = 0;
            for (int col = 0; col < n; col++) {
                sum += ints[col];
                sums[col] += sum;
                if (sums[col] <= k) {
                    ans++;
                } else {
                    break;
                }
            }
        }
        return ans;
    }
}