


You are given a matrix ‘M’ having dimensions ‘WIDTH x ‘HEIGHT’ and provided with an integer ‘N’. The matrix ‘M’ can take only binary values, i.e., 0 and 1. Your task is to find the “maximum number of ones” that the matrix ‘M’ can have such that every square sub-matrix of M of dimensions ‘N’ x ‘N’ has no more than ‘MAXONES’ ones.
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the T test cases follow.
The first and only line of each test case contains four positive integers, ‘WIDTH’, ‘HEIGHT’, ‘N’, and ‘MAXONES’, as described in the problem statement.
Output Format:
For each test case, print a single line containing a single integer denoting the maximum number of ones that the matrix M can have.
The output for each test case will be printed in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= ‘T’ <= 10
1 <= ‘WIDHT’, ‘HEIGHT’ <= 1000
1 <= ‘N’ <= WIDHT, HEIGHT
0 <= ‘MAXONES’ <= N * N
Where ‘T’ is the number of test cases, ‘WIDHT’ x ‘HEIGHT’ is the dimension of the matrix, ‘N’ * ‘N’ is the dimension of the square sub-matrix, and ‘MAXONES’ is the maximum number of ones a square sub-matrix can have.
Time Limit: 1sec.
1
2 2 1 1
4
In a 2*2 matrix, each 1*1 sub-matrix can have at most 1 one. So, the best solution will be:
[1, 1]
[1, 1]
1
3 3 2 0
0
Each sub-matrix of dimensions 2*2 must have 0 ones. So, the matrix M must contain all entries to be 0:
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
Try to divide the matrix into non-overlapping sub-matrices.
O((N ^ 2) * log(N ^ 2)), where N * N is the dimensions of the sub-matrix.
We are creating an array of size N * N that contains all the subMatrix elements, and we are sorting this array. So, the time complexity will be O((N ^ 2) * log(N ^ 2)).
O(N ^ 2), where N * N is the dimensions of the sub-matrix.
As we are creating an extra matrix and an array both of size N * N. Hence, the space complexity will be O(N ^ 2).