[leetcode刷题系列]Largest Rectangle in Histogram

经典题了, 利用stack优化, O(n)


const int MAXN = 1e6 + 10;

int n;
int pleft[MAXN], pright[MAXN];
stack<int> stk;

class Solution {

public:
    int largestRectangleArea(vector<int> &height) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        n = height.size();
        //left
        for(int i = n - 1; i >= 0; -- i){
            while(!stk.empty()){
                int now = stk.top();
                if(height[i] < height[now]){
                    pleft[now] = i;
                    stk.pop();
                }else break;
            }
            stk.push(i);
        }
        while(!stk.empty()){
            pleft[stk.top()] = -1;
            stk.pop();
        }
        // right
        for(int i = 0; i < n; ++ i){
            while(!stk.empty())
                if(height[i] < height[stk.top()]){
                    pright[stk.top()] = i;
                    stk.pop();
                }else break;
            stk.push(i);
        }
        while(!stk.empty()){
            pright[stk.top()] = n;
            stk.pop();
        }
        int ans = 0;
        for(int i = 0; i < n; ++ i)
            ans = max(ans, height[i] *(pright[i] - pleft[i] - 1));
        return ans;
    }
};


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