Leetcode 84. Largest Rectangle in Histogram

来源:互联网 发布:pic16f877a单片机 编辑:程序博客网 时间:2024/06/08 19:00
/** * Basic idea is using a stack to record the ascending heights in the given array. * Every time meet a height that is smaller than the previous one, pop out the statck, find the maximum area from  * heights stored in the statck, then push that smaller height into the array.  * Rpeat previous steps. */ public class Solution {    public int largestRectangleArea(int[] heights) {        int maxArea = 0;        Stack<Integer> stack = new Stack<>();        for (int i=0; i<=heights.length; i++) {            int curr = (i==heights.length) ? 0 : heights[i];            // found a height that destroys the ascending order            while (!stack.isEmpty() && curr < heights[stack.peek()]) {                int h = heights[stack.pop()];                int w = stack.isEmpty() ? i : i - stack.peek() - 1;                maxArea = Math.max(maxArea, h*w);            }            // push i into the stack b/c i >= stack.peek()            stack.push(i);        }                return maxArea;    }}

0 0
原创粉丝点击