leetcode85.最大矩形


leetcode85.最大矩形

题目

给定一个仅包含 01 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

用例

输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:6
解释:最大矩形如上图所示。
输入:matrix = []
输出:0
输入:matrix = [["0"]]
输出:0
输入:matrix = [["1"]]
输出:1
输入:matrix = [["0","0"]]
输出:0

求解

/**
 * @param {character[][]} matrix
 * @return {number}
 */
var maximalRectangle = function(matrix) {
    let max_Area = 0
    for(let i=0;i=0){
                if(matrix[p][j]==0){
                    break
                }
                height++
                p--
            }
            heights.push(height)
        }
        let tmp = largestArea(heights)
        tmp>max_Area?max_Area=tmp:max_Area=max_Area 
    }

    return max_Area


    function largestArea(heights){
        let height_stack = []
        let index_stack = []
        let maxArea = 0
        //哨兵
        heights[heights.length]=0
        height_stack.push(heights[0])
        index_stack.push(0)
        let final_index = 0
        let flag = false
        let i =1
        while(imaxArea?maxArea=weight*height:maxArea=maxArea
            }else if(heights[i]==height_stack[height_stack.length-1]){
                flag=false
                //相等的情况直接无视
                i++
            }else{
                //入栈
                //如果是出栈以后的入栈
                if(flag==true){
                    height_stack.push(heights[i])
                    index_stack.push(final_index)
                    flag=false
                }else{
                    height_stack.push(heights[i])
                    index_stack.push(i)
                }
                i++            
            }
        }
        return maxArea
    }
};

相关