#B4005. Largest Balanced Subrectangle

    ID: 11662 Type: Default 1000ms 256MiB

Largest Balanced Subrectangle

Largest Balanced Subrectangle

You are given an n x m grid where each cell is either black or white. A subrectangle of the grid is considered balanced if the number of black cells is equal to the number of white cells. Formally, if we assign a value of $-1$ to a black cell and $+1$ to a white cell, then a subrectangle is balanced if the sum of its values is $0$.

Your task is to determine the maximum number of cells in any balanced subrectangle in the grid.

Note: If no balanced subrectangle exists, the answer is 0.

Hint: One approach is to convert the grid into a matrix of $\pm1$ values and then, for every pair of rows, collapse the grid into a one-dimensional array. You can then find the largest subarray with sum zero using a prefix sum hash map. The overall complexity of this method is $O(n^2\cdot m)$.

inputFormat

The first line contains two integers n and m — the number of rows and columns of the grid, respectively.

The following n lines each contain a string of length m consisting only of characters 'B' and 'W', where 'B' represents a black cell and 'W' represents a white cell.

outputFormat

Output a single integer — the maximum number of cells in a balanced subrectangle.

sample

2 2
BW
WB
4