[leetcode] Largest Rectangle in Histogram

Largest Rectangle in Histogram


class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        stack<int> stk;
        height.push_back(0);
        int res=0;
        
        for(int i=0;i<height.size();){
            if(stk.empty()||height[i]>height[stk.top()]){
                stk.push(i++);
            }else{
                int tmp=stk.top();
                stk.pop();
                res=max(res,height[tmp]*(stk.empty()?i:(i-stk.top()-1)));
            }
        }
        return res;
    }
};

class Solution {//时间复杂度O(n)
public:
    int largestRectangleArea(vector<int>& height) {
        int n=height.size();
        int res=0;
        stack<int> stk;
        for(int i=0;i<n;++i){
            while((!stk.empty())&&(height[stk.top()]>=height[i])){//
                //出栈
                int h=height[stk.top()];
                stk.pop();
                //计算面积:如果栈空,最左侧为-1
                res=max(res,(i-1-(stk.empty()?(-1):stk.top()))*h);
            }
            stk.push(i);//下标i入栈
        }
        while(!stk.empty()){
            int h=height[stk.top()];
            stk.pop();
            res=max(res,(n-1-(stk.empty()?(-1):stk.top()))*h);
        }
        return res;
    }
};


你可能感兴趣的:([leetcode] Largest Rectangle in Histogram)