直方圖內最大矩形

題目
公司:美團
類型:單調棧
題意:找到一個數組中形成的最大矩形。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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章