

The largest sub-matrix having an equal number of 0s and 1s in the above grid is shown below :

The area of the largest sub-matrix having an equal number of 0s and 1s is 4(rows in highlighted image) * 2(columns in highlighted image) = 8.
The first line of input contains an integer ‘T’ denoting the number of test cases. Then each test case follows.
The first line of each test case contains two single space-separated integers ‘N’ and ‘M’ representing the number of rows and columns of the grid, respectively.
The next 'N' lines of each test case contain 'M' single space-separated integers 0 or 1.
For each test case, print the area of the largest possible sub-matrix having an equal number of 0s and 1s.
Print the output of each test case in a separate line.
You don’t have to print anything, it has already been taken care of. Just complete the function.
1 <= T <= 10^2
1 <= N <= 50
1 <= M <= 50
MAT[i][j] = 0 or 1
Time Limit: 1 sec
We will naively count 0s and 1s in all possible submatrices and return the area of the largest submatrix having an equal number of 0s and 1s.
We will replace all 0s in the matrix by -1. Now we will find the submatrices with 0 sum and return the area of largest of them. A matrix with 0 sum has equal number of -1s and 1s, i.e. equal number of 0s and 1s.
We will use the prefix sum of the grid to calculate the sum of elements of a sub-matrix in O(1) time complexity.
In this approach, we fix the left and right columns one by one and find the largest sub-array with contiguous rows sum 0 for every left and right column pair. Simply, we are finding the maximum length (top and bottom row) having sum 0 for every left and right column pair.
Here is the algorithm: