
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find area of largest submatrix by column rearrangements in Python
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]
- if matrix[i, j] is 1, then
- for j in range 0 to m - 1, do
- 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[0]) 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
- Related Articles
- Program to find largest submatrix with rearrangements in Python
- Program to find area of largest island in a matrix in Python
- Program to find largest rectangle area under histogram in python
- Program to find area of largest square of 1s in a given matrix in python
- C++ Program to Find Largest Rectangular Area in a Histogram
- Program to find total area covered by two rectangles in Python
- Program to find largest merge of two strings in Python
- Largest Triangle Area in Python
- C++ program to find the Area of the Largest Triangle inscribed in a Hexagon?
- Program to find the sum of largest K sublist in Python
- Program to find largest product of three unique items in Python
- Python Program to find largest element in an array
- Python program to find largest number in a list
- Program to Find K-Largest Sum Pairs in Python
- Program to find lexicographically largest mountain list in Python

Advertisements