Description
You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order.
Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.
Example 1:
Input: matrix = [[0,0,1],[1,1,1],[1,0,1]] Output: 4 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4.
Example 2:
Input: matrix = [[1,0,1,0,1]] Output: 3 Explanation: You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3.
Example 3:
Input: matrix = [[1,1,0],[1,0,1]] Output: 2 Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m * n <= 105matrix[i][j]is either0or1.
Solutions
This algorithm finds the largest rectangular submatrix of 1s in a binary matrix. First, it transforms the matrix by stacking consecutive 1s vertically—each cell becomes the count of 1s above it (including itself), creating a "height map" for each row. Then for each row, it sorts these heights in descending order and calculates the maximum area by treating each height as the rectangle's dimension: for a height at position j, the width is j + 1 (since smaller or equal heights exist at positions 0 to j), so area = height × (j + 1). The algorithm tracks the maximum area found across all rows and positions.
/**
* @param {number[][]} matrix
* @return {number}
*/
const largestSubmatrix = matrix => {
const m = matrix.length;
const n = matrix[0].length;
let max = 0;
for (let i = 1; i < m; i++)
for (let j = 0; j < n; j++)
if (matrix[i][j] === 1)
matrix[i][j] += matrix[i - 1][j];
for (let i = 0; i < m; i++) {
matrix[i].sort((j, k) => k - j);
for (let j = 0; j < n; j++)
max = Math.max(max, matrix[i][j] * (j + 1));
}
return max;
};