leetcode-84. 柱状图中最大的矩形

为了使得最后一块板子也被处理,这里用了个小trick,在高度数组最后面加上一个0,这样原先的最后一个板子也可以被处理了
class Solution {  
public:  
    int Max(int a, int b){return a > b ? a : b;}  
    int largestRectangleArea(vector<int> &height) {  
        height.push_back(0);  
        stack<int> stk;  
        int i = 0;  
        int maxArea = 0;  
        while(i < height.size()){  
            if(stk.empty() || height[stk.top()] <= height[i]){  
                stk.push(i++);  
            }else {  
                int t = stk.top();  
                stk.pop();  
                maxArea = Max(maxArea, height[t] * (stk.empty() ? i : i - stk.top() - 1));  
            }  
        }  
        return maxArea;  
    }  
};

猜你喜欢

转载自blog.csdn.net/qq_39370495/article/details/89428068