【代码随想录刷题笔记 Day 60】 84.柱状图中最大的矩形

 84.柱状图中最大的矩形
题目

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

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

示例

【代码随想录刷题笔记 Day 60】 84.柱状图中最大的矩形_第1张图片

输入:heights = [2,1,5,6,2,3]
输出:10
解释:最大的矩形为图中红色区域,面积为 10
class Solution {
public:
    int largestRectangleArea(vector& heights) {
        int result = 0;
        stackst;
        heights.insert(heights.begin(),0);
        heights.push_back(0);
        st.push(0);
        for(int i = 1; i < heights.size(); i++)
        {
            while(!st.empty() && heights[i] < heights[st.top()])
            {
                int mid = heights[st.top()];
                st.pop();
                if(!st.empty())
                {
                    int w = i-st.top()-1;
                    result = max(result,w*mid);
                }
            }
            st.push(i);
        }
        return result;

    }
};

你可能感兴趣的:(笔记)