跳转至

84. 柱状图中最大的矩形

一、题目描述

给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。求在该柱状图中,能够勾勒出来的矩形的最大面积。

二、解题思路

单调栈O(n)遍历

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        stack<int> stk;
        int res = 0;
        heights.push_back(-1);
        for (int i = 0; i < heights.size(); ++i) {
            while (!stk.empty() && heights[i] < heights[stk.top()]) {
                int t = stk.top();
                stk.pop();
                int left = stk.empty() ? -1 : stk.top();
                res = max(res, (i - left - 1) * heights[t]);
            }
            stk.push(i);
        }
        return res;
    }
};