题解 | #直方图内最大矩形#

直方图内最大矩形

https://www.nowcoder.com/practice/bfaac4eebe5947af80912d1bcfcf2baa

#include <algorithm>
#include <stack>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param heights int整型vector 
     * @return int整型
     */
    int largestRectangleArea(vector<int>& heights) {
        // write code here
        int n=heights.size();
        stack<int> s;
        int res=0;
        for(int i=0;i<n;i++){
            while(!s.empty()&&heights[s.top()]>heights[i]){
                int curheight=heights[s.top()];
                s.pop();
                int L=s.empty()?0:s.top()+1;
                res=max(res,(i-L)*curheight);
            }
            s.push(i);
        }
        while(!s.empty()){
            int curheight=heights[s.top()];
            s.pop();
            int L=s.empty()?0:s.top()+1;
            res=max(res,(n-L)*curheight);
        }
        return res;
    }
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务