题目

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.

image.png
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

image.png
The largest rectangle is shown in the shaded area, which has area = 10 unit.

Example:

  1. Input: [2,1,5,6,2,3]
  2. Output: 10

题意

在直方图中找到面积最大的矩形。

思路

参考[LeetCode] 84. Largest Rectangle in Histogram 直方图中最大的矩形以及LeetCode 笔记系列 17 Largest Rectangle in Histogram


代码实现

Java

  1. class Solution {
  2. public int largestRectangleArea(int[] heights) {
  3. int ans = 0;
  4. Deque<Integer> stack = new ArrayDeque<>();
  5. int i = 0;
  6. int[] copy = Arrays.copyOf(heights, heights.length + 1);
  7. while (i < copy.length) {
  8. if (stack.isEmpty() || copy[i] > copy[stack.peek()]) {
  9. stack.push(i++);
  10. } else {
  11. int h = copy[stack.pop()];
  12. int w = stack.isEmpty() ? i : i - stack.peek() - 1;
  13. ans = Math.max(ans, h * w);
  14. }
  15. }
  16. return ans;
  17. }
  18. }