• 84. 柱状图中最大的矩形


    题目

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

    以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。

    图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。

    输入: [2,1,5,6,2,3]
    输出: 10

    分析

    • 对于一个高度,如果能得到向左和向右的边界
    • 那么就能对每个高度求一次面积
    • 遍历所有高度,即可得出最大面积
    • 使用单调栈,在出栈操作时得到前后边界并计算面积

    单调栈的编码技巧

    • 为了边界的通过,注意加入"哨兵"。
    • 单调栈往往存储的是数组的索引。
    class Solution {
    public:
        int largestRectangleArea(vector<int>& heights) {
            int ans = 0;
            stack<int> st;
            
            // 加入哨兵
            heights.push_back(0);
            heights.insert(heights.begin(), 0);
    
            for(int i = 0; i < heights.size(); i++){
                
                while (!st.empty()  && heights[st.top()] > heights[i]){
                    int cur = st.top();
                    st.pop();
                    int right = i - 1;
                    int left = st.top() + 1;
                    ans = max(ans, (right - left + 1) * heights[cur]);
                }
                st.push(i);
            }
            return ans;
        }
    };
    
    

    单调栈的模板

    stack<int> st;
    for(int i = 0; i < nums.size(); i++)
    {
    	while(!st.empty() && st.top() > nums[i])
    	{
    		st.pop();
    	}
    	st.push(i);
    }
    
  • 相关阅读:
    cv2 Qt Platform plugin "cocoa" not found error
    开发scrapy web界面(一)
    java2smali python 粘合脚本
    react如何设置代理
    Nginx启动不了失败原因
    前端,后端,服务器如何部署,转载
    匿名函数普通函数和构造函数
    闭包的认识
    各种命名规范,打好基础才能建设高楼
    mongoose常用操作
  • 原文地址:https://www.cnblogs.com/wsl-hitsz/p/14193914.html
Copyright © 2020-2023  润新知