单调栈系列~LeetCode84.柱状图中最大的矩形(困难)

class Solution {
   
    public int largestRectangleArea(int[] heights) {
   
        int len = heights.length;
        int []left = new int[len];
        int []right = new int[len];
        Stack<Integer> stack = new Stack<>();
        for(int i=0; i<len; i++){
   //从前往后找当前元素后面的比他小的最小元素
            while(!stack.isEmpty() && heights[i] <= heights[stack.peek()]){
   
                stack.pop();
            }
            if(stack.isEmpty()){
   
                left[i] = -1;
            }else{
   
                left[i] = stack.peek();
            }
            stack.push(i);
        }
        stack.removeAllElements();//将栈中的元素清空
        for(int i=len-1; i>=0; i--){
   //从后向前找当前元素后面的比他小的最小元素
            while(!stack.isEmpty() && heights[i] <= heights[stack.peek()]){
   
                 stack.pop();
            }
            if(stack.isEmpty()){
   
                right[i] = len;
            }else{
   
                right[i] = stack.peek();
            }
            stack.push(i);
        }
        int max = 0;
        for(int i=0; i<len; i++){
   
            max = Math.max(max, heights[i] * (right[i] - left[i] - 1));
        }
        return max;
    }
}
全部评论

相关推荐

EEbond:给北邮✌️跪了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务