84. Largest Rectangle in Histogram(单调栈)

题目链接
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.

84. Largest Rectangle in Histogram(单调栈)_第1张图片
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

84. Largest Rectangle in Histogram(单调栈)_第2张图片

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

Example:

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

题意:
给定n个非负整数代表n个柱形条的高度,每个柱形条的宽度都是1,返回该柱形图中最大矩形的面积。

84. Largest Rectangle in Histogram(单调栈)_第3张图片

以上是一个柱形图,每个柱形条的宽度是1,高度为[2,1,5,6,2,3]。

84. Largest Rectangle in Histogram(单调栈)_第4张图片

最大的矩形如上图所示,面积为10

题解:对于每个数的左边和右边进行两次单调栈,找到它左边比它最后一个高的柱体的下标和右边比它最后一个高的柱体的下标,最后遍历一遍数组找到柱体最大值

int largestRectangleArea(vector<int>& heights) {
        stack <pair<int,int>> stk;
        vector <int> forward(heights.size()),backward(heights.size());
        for(int i = 0;i < heights.size();i++){
            forward[i] = i;
            while(!stk.empty() && heights[i] <= stk.top().first){
                forward[i] = stk.top().second;
                stk.pop();
            }
            stk.push({heights[i],forward[i]});
        }
        while(!stk.empty()) stk.pop();
        for(int i = heights.size() - 1;~i;i--){
            backward[i] = i;
            while(!stk.empty() && heights[i] <= stk.top().first){
                backward[i] = stk.top().second;
                stk.pop();
            }
            stk.push({heights[i],backward[i]});
        }
        int res = 0;
        for(int i = 0;i < heights.size();i++)
            res = max(res,heights[i] * (backward[i] - forward[i] + 1));
        return res;
    }

你可能感兴趣的:(栈)