[leetcode]84. Largest Rectangle in Histogram(Java)

来源:互联网 发布:知乎哲理段落 编辑:程序博客网 时间:2024/06/03 16:21

https://leetcode.com/problems/largest-rectangle-in-histogram/#/description


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.

For example,
Given heights = [2,1,5,6,2,3],
return 10.


package go.jacob.day702;import java.util.Stack;public class Demo2 {/* * Runtime: 24 ms.Your runtime beats 67.12 % of java submissions. */public int largestRectangleArea(int[] heights) {if (heights == null || heights.length < 1)return 0;Stack<Integer> stack = new Stack<Integer>();stack.push(-1);int max = 0;for (int i = 0; i < heights.length; i++) {// 把堆栈中比heights[i]大的元素都pop出,并计算面积while (stack.peek() != -1 && heights[i] < heights[stack.peek()]) {int top = stack.pop();// 面积计算公式:(i - 1-stack.peek() ) * heights[top])max = Math.max(max, (i - 1 - stack.peek()) * heights[top]);}stack.push(i);}while (stack.peek() != -1) {int top = stack.pop();max = Math.max(max, (heights.length - 1 - stack.peek()) * heights[top]);}return max;}}


原创粉丝点击