代码随想录算法训练营day 60 |84.柱状图中最大的矩形

84.柱状图中最大的矩形

代码随想录

不太熟练,和上一个题放在一起做

代码:

class Solution {
    public int largestRectangleArea(int[] heights) {
        int[] temp = new int[heights.length+2];
        for(int i = 1; i < temp.length - 1; i++){
            temp[i] = heights[i-1];
        }
        heights = temp;
        Deque stack = new LinkedList<>();
        int res = 0;
        stack.push(0);
        for(int i = 1; i < heights.length; i++){
            while(!stack.isEmpty() && heights[stack.peek()] > heights[i]){
                int height = heights[stack.peek()];
                stack.pop();
                int leftIndex = stack.peek();
                int w = i - leftIndex - 1;
                res = Math.max(res, w*height); 
            }
            stack.push(i);
        }
        return res;
    }
}

你可能感兴趣的:(算法,leetcode,数据结构)