1. Problem Statement
We are given a binary matrix containing only 0 and 1.
We are allowed to swap any two columns any number of times.
Our goal is to find the maximum possible area of a rectangle containing only 1s after performing column swaps.
For example:
0 1 0 1 0
0 1 0 1 1
1 1 0 1 0The answer is:
6The important observation is that we are allowed to rearrange columns, so we don't need to preserve their original order.
2. Main Idea
We process the matrix row by row.
For every column, we maintain the number of continuous 1s ending at the current row.
For example:
0 1 1
1 1 1
1 1 0After processing row 0:
0 1 1After processing row 1:
1 2 2After processing row 2:
2 3 0Here:
height[j]represents the number of consecutive 1s in column j ending at the current row.
3. Why Can We Sort the Heights?
This is the most important part of the problem.
Suppose at some row we have:
height = [2, 5, 3, 1, 4]Because columns can be swapped, we can rearrange them as:
[5, 4, 3, 2, 1]Now the largest heights can be placed next to each other.
For example:
5 4 3 2 1If we choose the first 3 columns, the minimum height is 3.
Therefore, we can create:
Height = 3
Width = 3
Area = 3 × 3 = 9So after sorting, we simply check every possible width.
4. Java Code
import java.util.*;
class Solution {
public int maxArea(int[][] mat) {
int n = mat.length;
int m = mat[0].length;
int[] height = new int[m];
int maxArea = 0;
for (int i = 0; i < n; i++) {
// Calculate consecutive 1s for each column
for (int j = 0; j < m; j++) {
if (mat[i][j] == 1) {
height[j]++;
} else {
height[j] = 0;
}
}
// Copy heights
int[] sorted = height.clone();
// Sort heights
Arrays.sort(sorted);
// Try every possible width
for (int j = m - 1; j >= 0; j--) {
int width = m - j;
int area = sorted[j] * width;
maxArea = Math.max(maxArea, area);
}
}
return maxArea;
}
}5. Line-by-Line Explanation
Step 1: Get matrix dimensions
int n = mat.length;
int m = mat[0].length;n = number of rows.
m = number of columns.
For:
3 × 5we have:
n = 3
m = 5Step 2: Create the height array
int[] height = new int[m];This stores the number of consecutive 1s for every column.
Initially:
height = [0, 0, 0, 0, 0]Step 3: Process every row
for (int i = 0; i < n; i++) {We process one row at a time.
Step 4: Update the heights
for (int j = 0; j < m; j++) {
if (mat[i][j] == 1) {
height[j]++;
} else {
height[j] = 0;
}
}If the current cell is 1:
height[j]++;We increase the consecutive height.
If the current cell is 0:
height[j] = 0;The consecutive sequence is broken.
Example
Consider:
1 1 0
1 1 1
1 0 1After first row:
1 1 0After second row:
2 2 1After third row:
3 0 2So the height array represents vertical rectangles ending at the current row.
6. Copy the Heights
int[] sorted = height.clone();We create a copy because we don't want to modify the original height array.
For example:
height = [3, 1, 4, 2]After cloning:
sorted = [3, 1, 4, 2]7. Sort the Heights
Arrays.sort(sorted);After sorting:

Join the conversation! Your thoughts help the community grow.