直方图内最大矩形

题目
公司:美团
类型:单调栈
题意:找到一个数组中形成的最大矩形。leetcode84题原题。

class MaxInnerRec {
public:
    int countArea(vector<int> A, int n) {
        //单调栈
        stack<int> stk;
        stk.push(-1);
        int res = 0;
        for(int i = 0; i < n; i++){
            while(stk.top() != -1 && A[stk.top()] >= A[i]){
                int h = A[stk.top()];
                stk.pop();
                res = max(res, h *(i - stk.top()-1));
            }
            stk.push(i);
        }
        while(stk.top()!=-1){
             int h = A[stk.top()];
             stk.pop();
             res = max(res, h *(n - stk.top()-1));
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章