85. Maximal Rectangle (JAVA)

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

 


Above is a histogram where width of each bar is 1, given height =[2,1,5,6,2,3].

 


The largest rectangle is shown in the shaded area, which has area =10 unit.

 

Example:

Input: [2,1,5,6,2,3]
Output: 10

84. Largest Rectangle in Histogram的升级版: 按行按列分别做动态规划

class Solution {
    public int maximalRectangle(char[][] matrix) {
        if(matrix.length == 0 ) return 0;
        
        int width = matrix[0].length;
        int height = matrix.length;
        int maxArea = 0;
        int area;
        
        //按列动态规划,求出到此位置最多连续为1的次数
        int[][] dp = new int[height][width];
        for(int i = 0; i < width; i++){
            for(int j = 0; j < height; j++){
                dp[j][i] = matrix[j][i] - '0';
                if(matrix[j][i] == '1' && j > 0){
                    dp[j][i] += dp[j-1][i];
                }
            }
        }
        
        //按行动态规划,求出最大面积
        for(int i = 0; i < height; i++){
            area = largestRectangleArea(dp[i]);
            if(area > maxArea) maxArea = area;
        }
        return maxArea;
    }
    
    public int largestRectangleArea(int[] heights) {
        Stack<Integer> st = new Stack<Integer>(); 
        if(heights.length == 0) return 0;
        
        int leftIndex;
        int topIndex;
        int area;
        int maxArea = 0; 
        int i = 0;
        while(i < heights.length){
            if(st.empty() || heights[i] >= heights[st.peek()]){
                st.push(i);
                i++;
            }
            else{
                topIndex = st.peek();
                st.pop();
                leftIndex = st.empty()?0:st.peek()+1; //如果是空,说明从头开始的所有高度都比heights[topIndex]高
                area = ((i-1)-leftIndex + 1) * heights[topIndex];
                if(area > maxArea) maxArea = area;
            }
        }
        while(!st.empty()){ //没有比栈顶元素小的元素让它出栈
            topIndex = st.peek();
            st.pop();
            leftIndex = st.empty()?0:st.peek()+1; 
            area = ((i-1)-leftIndex + 1) * heights[topIndex];
            if(area > maxArea) maxArea = area;
        }
        return maxArea;
    }
}

 

转载于:https://www.cnblogs.com/qionglouyuyu/p/10949885.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值