Given a rows x cols binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
Example 1: Input: matrix = [ [“1”,”0”,”1”,”0”,”0”], [“1”,”0”,”1”,”1”,”1”], [“1”,”1”,”1”,”1”,”1”], [“1”,”0”,”0”,”1”,”0”] ] Output: 6 Explanation: The maximal rectangle is shown in the above picture.
Example 2: Input: matrix = [[“0”]] Output: 0
Example 3: Input: matrix = [[“1”]] Output: 1
Constraints: rows == matrix.length cols == matrix[i].length 1 <= row, cols <= 200 matrix[i][j] is ‘0’ or ‘1’.
/** * @param {character[][]} matrix * @return {number} */ var maximalRectangle = function(matrix) { // corner case if (matrix == null || matrix.length == 0) { return0; }
// normal case let res = 0; let row = matrix.length; let col = matrix[0].length; let heights = newArray(col).fill(0); for (let i = 0; i < row; i++) { for (let j = 0; j < col; j++) { if (matrix[i][j] == '1') { heights[j]++; } else { heights[j] = 0; } } let area = helper(heights); res = Math.max(res, area); } return res; };
var helper = function(heights) { // corner case if (heights == null || heights.length == 0) { return0; }
// normal case let stack = []; let res = 0; for (let i = 0; i <= heights.length; i++) { let h = i == heights.length ? 0 : heights[i]; while (stack.length && h < heights[stack[stack.length - 1]]) { let height = heights[stack.pop()]; let start = !stack.length ? -1 : stack[stack.length - 1]; let area = height * (i - start - 1); res = Math.max(res, area); } stack.push(i); } return res; };
相关题目
1 2 3 4 5
84. Largest Rectangle in Histogram 85. Maximal Rectangle 221. Maximal Square 1277. Count Square Submatrices with All Ones 1727. Largest Submatrix With Rearrangements