![]() |
VOOZH | about |
Given a matrix arr[][] of size NxM and an integer K, the task is to find the count of square submatrices in the given matrix with the average of elements greater than or equal to K.
Examples:
Input: K = 4, arr[][] = {{2, 2, 3}, {3, 4, 5}, {4, 5, 5}}
Output: 7
Explanation:
The following square submatrices have an average greater than or equal to K:
- Square submatrices of dimension (1×1), formed by taking the elements at positions {(2, 2)}. The average of the submatrix is equal to 4.
- Square submatrices of dimension (1×1), formed by taking the elements at positions {(2, 3)}. The average of the submatrix is equal to 5.
- Square submatrices of dimension (1×1), formed by taking the elements at positions {(3, 1)}. The average of the submatrix is equal to 4.
- Square submatrices of dimension (1×1), formed by taking the elements at positions {(3, 2)}. The average of the submatrix is equal to 5.
- Square submatrices of dimension (1×1), formed by taking the elements at positions {(3, 3)}. The average of the submatrix is equal to 5.
- Square submatrices of dimension (2×2), formed by taking the elements at positions {(2, 1), (2, 2), (3, 1), (3, 2)}. The average of the submatrix is equal to (3+4+4+5 = 16)/4 = 4.
- Square submatrices of dimension (2×2), formed by taking the elements at positions {(2, 2), (2, 3), (3, 2), (3, 3)}. The average of the submatrix is equal to (4+5+5+5 = 19)/4 = 4.75.
Therefore, there are totals of 7 square submatrices with an average greater than or equals to K.
Input: K = 3, arr[][] = {{1, 1, 1}, {1, 1, 1}}
Output: 0
Naive Approach: The simplest approach is to generate all possible square submatrices and check sum of all the elements of the sub-square is greater than or equals to K multiplied by the size of the submatrix.
Time Complexity: O(N3 * M3)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized using the prefix sum matrix which results in constant time calculation of the sum of a submatrix. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
c
7
Time Complexity: O(M * N * (min(N, M))
Auxiliary Space: O(M * N)