Largest Rectangle in Histogram

来源:互联网 发布:猪八戒淘宝直播 编辑:程序博客网 时间:2024/06/16 02:57
public class Solution {    public int largestRectangleArea(int[] heights) {    if (heights == null) {        throw new IllegalArgumentException("");    }    if (heights.length == 0) {        return 0;    }    int maxArea = 0;    Stack<Integer> stack = new Stack<>();    for (int i = 0; i < heights.length; i++) {        if (stack.isEmpty()) {            stack.push(i);        } else {            while (!stack.isEmpty() && heights[i] < heights[stack.peek()]) {                //int last_height = stack.pop();                int last_height = heights[stack.pop()];                if (!stack.isEmpty()) {                    maxArea = Math.max(maxArea, (i - 1 - stack.peek())*last_height);                } else {                    maxArea = Math.max(maxArea, i*last_height);                }            }            stack.push(i);        }    }    while (!stack.isEmpty()) {        //int last_height = stack.pop();        int last_height = heights[stack.pop()];            if (!stack.isEmpty()) {                maxArea = Math.max(maxArea, (heights.length - 1 - stack.peek())*last_height);            } else {                maxArea = Math.max(maxArea, heights.length*last_height);            }    }    return maxArea;    }}

0 0
原创粉丝点击