You are given a matrix “mat” of size ‘m’ * ‘n’ and an integer “val”. You need to find the maximum length of the side of a square having sum not greater than “val”.
If there is no such square, return 0.
For Example :m = 4, n = 3, mat = {{1, 1, 1}, {2, 1, 2}, {1, 2, 1}, {1, 1, 1}}, val = 5.
In this example, the maximum value of length of side which can be obtained is 2, Having the starting index: {0, 0} or {0, 1} or {2, 0} or {2, 1}.
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows:
The first line of each test case contains two integers ‘n’ and ‘m’ denoting the dimensions of the matrix.
The next ‘n’ lines contain ‘m’ integer where the jth integer of the ith line denotes the value at “mat[i][j]”.
The next line contains a single integer “val” denoting the maximum sum needed.
Output Format :
For each test case, print a single integer “ans” denoting the maximum side of the square.
Output for each test case will be printed in a separate line.
Note :
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N, M <= 300
1 <= mat[i][j] <= 5000
1 <= val <= 50000
Time limit: 1 sec
2
4 2
1 1
1 1
1 1
1 1
25
3 3
3 3 3
3 1 3
3 3 3
2
2
1
In the first test case, val is high enough, so we can take a square of the maximum side, which is 2.
Hence the answer is 2.
In the second test case, val is 2, hence the only square matrix having the sum of value less than 2 is {{1}}, having side equal to 1.
Hence the answer is 1.
2
1 5
1 4 2 3 4
100
6 4
1 8 7 3
4 2 9 7
1 2 7 1
88 5 4 11
4 2 6 2
8 45 66 5
11
1
2
Create a 2D prefix sum array, and check for every square matrix whether the sum is less than “val” or not.
In this approach, we will iterate through all the square matrices and check whether the sum of the matrix is less than “val” and return the value of the side of the matrix having the maximum length.
The steps are as follows:
O( M * N * min(M*N) ), where M, N are the dimensions of the matrix.
As we are checking all the square matrices.
Hence the time complexity is O( M * N * min(M*N) ).
O( M * N ), where M, N are the dimensions of the matrix.
As we are using a 2D array to store the prefix sum
Hence the space complexity is O( M * N ).