# Program to find area of largest submatrix by column rearrangements in Python

PythonServer Side ProgrammingProgramming

Suppose we have a binary matrix. We can first rearrange the columns as many times as we want, then find return the area of the largest submatrix containing only 1s.

So, if the input is like

 1 0 0 1 1 1 1 0 1

then the output will be 4, because we can arrange is like −

 1 0 0 1 1 1 1 1 0

To solve this, we will follow these steps −

• n := row count of matrix
• m := column count of matrix
• ans := 0
• for i in range 1 to n - 1, do
• for j in range 0 to m - 1, do
• if matrix[i, j] is 1, then
• matrix[i, j] := matrix[i, j] + matrix[i-1, j]
• for each row in matrix, do
• sort the row
• for j in range m-1 to 0, decrease by 1, do
• ans := maximum of ans and row[j] *(m - j)
• return ans

## Example

Let us see the following implementation to get better understanding −

def solve(matrix):
n, m = len(matrix), len(matrix)
ans = 0
for i in range(1, n) :
for j in range(m) :
if matrix[i][j] :
matrix[i][j] += matrix[i-1][j]
for row in matrix :
row.sort()
for j in range(m-1, -1, -1):
ans = max(ans, row[j] *(m - j))
return ans

matrix = [
[1, 0, 0],
[1, 1, 1],
[1, 0, 1]
]
print(solve(matrix))

## Input

[
[1, 0, 0],
[1, 1, 1],
[1, 0, 1]
]

## Output

4