题目

类型:Stack

难度:困难

柱状图中最大的矩形 - 图1

解题思路

https://leetcode-cn.com/problems/largest-rectangle-in-histogram/solution/zhu-zhuang-tu-zhong-zui-da-de-ju-xing-by-leetcode-/
看题解中的PPT有助于理解

代码

  1. class Solution {
  2. public int largestRectangleArea(int[] heights) {
  3. int n = heights.length;
  4. int[] left = new int[n];
  5. int[] right = new int[n];
  6. Arrays.fill(right, n);
  7. Stack<Integer> mono_stack = new Stack<Integer>();
  8. for (int i = 0; i < n; ++i) {
  9. while (!mono_stack.isEmpty() && heights[mono_stack.peek()] >= heights[i]) {
  10. right[mono_stack.peek()] = i;
  11. mono_stack.pop();
  12. }
  13. left[i] = (mono_stack.isEmpty() ? -1 : mono_stack.peek());
  14. mono_stack.push(i);
  15. }
  16. int ans = 0;
  17. for (int i = 0; i < n; ++i) {
  18. ans = Math.max(ans, (right[i] - left[i] - 1) * heights[i]);
  19. }
  20. return ans;
  21. }
  22. }