跳转至

柱状图中最大的矩形⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

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

        while (!stk.empty()) {
            int current = stk.top();
            stk.pop();
            int left = !stk.empty() ? stk.top() : -1;
            res = max(res, heights[current] * (n - left - 1));
        }

        return res;
    }
};