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

时间:2020-07-15 11:02:25   收藏:0   阅读:39

代码

class Solution {
public:
    int largestRectangleArea(vector<int>& h) {
        int n = h.size();
        vector<int> left(n), right(n);
        stack<int> stk;

        for (int i = 0; i < n; ++i) {
            while (stk.size() && h[stk.top()] >= h[i]) stk.pop();
            if (stk.empty()) left[i] = -1;
            else left[i] = stk.top();
            stk.push(i);
        }
        stk = stack<int>();

        for (int i = n - 1; i >= 0; --i) {
            while (stk.size() && h[stk.top()] >= h[i]) stk.pop();
            if (stk.empty()) right[i] = n;
            else right[i] = stk.top();
            stk.push(i);
        }

        int ans = 0;
        for (int i = 0; i < n; ++i) ans = max(ans, h[i] * (right[i] - left[i] - 1));
        return ans;
    }
};

原文:https://www.cnblogs.com/clown9804/p/13303787.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!