Leetcode:84. Largest Rectangle in Histogram(面積最大的長方形)
阿新 • • 發佈:2018-12-29
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
Example:
Input: [2,1,5,6,2,3]
Output: 10
方法1:
class Solution { public int largestRectangleArea(int[] heights) { if (heights == null || heights.length == 0) { return 0; } Stack<Integer> stack = new Stack<>(); int max = 0, i = 0; while (i <= heights.length) { if (stack.isEmpty() || (i < heights.length && heights[i] >= heights[stack.peek()])) { stack.push(i); i++; } else { int top = stack.pop(); int width = stack.isEmpty() ? i : i - stack.peek() - 1; max = Math.max(max, width * heights[top]); } } return max; } }
時間複雜度:O(n)
空間複雜度:O(n)