LeetCode 84. Maximal Rectanglea (O(n)实现)

来源:互联网 发布:java贪吃蛇教程 编辑:程序博客网 时间:2024/05/28 15:10

参考hackersun007的修行之路的题解,里面的几幅图很直观。

用一个栈维护单调递增的高度的下标,维护元素的压入弹出。


代码:

class Solution {public:    int largestRectangleArea(vector<int> &height)     {        height.push_back(-1); // dummy element        stack<int> s;        int maxx = 0;        for (int i = 0; i < height.size(); )        {            if (s.empty()==true || height[s.top()]<=height[i])            {                s.push(i ++); // -1 will be pushed at last, and nothing will happen            } else             {                int top_index = s.top();                s.pop();                maxx = max(maxx, height[top_index]*(s.empty()? i: i-s.top()-1));            }        }        return maxx;    }};


0 0