剑指offer039-直方图最大矩形面积

直方图最大矩形面积

Posted by 高明 on 2020-01-01

剑指offer039-直方图最大矩形面积

题目

给定非负整数数组 heights ,数组中的数字用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1

求在该柱状图中,能够勾勒出来的矩形的最大面积。

 

示例 1:

输入:heights = [2,1,5,6,2,3]
输出:10
解释:最大的矩形为图中红色区域,面积为 10

示例 2:

输入: heights = [2,4]
输出: 4

 

提示:

  • 1 <= heights.length <=105
  • 0 <= heights[i] <= 104

 

注意:本题与主站 84 题相同: https://leetcode-cn.com/problems/largest-rectangle-in-histogram/

Related Topics
  • 数组
  • 单调栈

  • 👍 15
  • 👎 0
  • 思路

    这题目很多次了,单调栈解决

    代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    class Solution {
    public int largestRectangleArea(int[] heights) {
    Stack<Integer> stack = new Stack<>();
    stack.push(-1);
    int m = Integer.MIN_VALUE;
    for (int i = 0; i < heights.length; i++) {
    while (stack.peek() != -1 && heights[i] < heights[stack.peek()]) {
    int height = heights[stack.pop()]; // 3
    int width = i - stack.peek() - 1;
    m = Math.max(m, height * width);
    }
    stack.push(i);
    }

    while (stack.peek() != -1) {
    int height = heights[stack.pop()]; // 3
    int width = heights.length - stack.peek() - 1;
    m = Math.max(m, height * width);
    }
    return m;
    }
    }