Day60 单调栈 LC 84

16 阅读1分钟

84. 柱状图中最大的矩形

心得

  • 多看,多了解思路

题解

  • 核心找到一个三元组,(left, mid, right),找到base后左右找到小于的第一个值,决定了以该base横向划线的宽度,即为面积,保存最值即可

  • 注意和接雨水区分

    • 单调递减栈
    • 加前后缀,由于是三元组,匹配首位位置无元素情况,也是针对原序列升降序情况
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        stack<int> st;
        heights.insert(heights.begin(), 0); // 解决原序列降序时,栈第一个元素没有left
        heights.push_back(0); // 原序列升序,最后一个没有right
        int result = 0; 
        st.push(0);
        for (int i = 1; i < heights.size(); i++) {
            if (heights[i] > heights[st.top()]) {
                st.push(i);
            } else if (heights[i] == heights[st.top()]) {
                st.pop();
                st.push(i);
            } else {
                while (!st.empty() && heights[i] < heights[st.top()]) {
                    int mid = st.top();
                    st.pop();
                    if (!st.empty()) {
                        int left = st.top();
                        int right = i;
                        int w = right - left - 1;
                        int h = heights[mid];
                        result = max(result, w * h); 
                    }
                }
                st.push(i);
            }
        }
        return result;
    }
};

// 精简
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        stack<int> st;
        heights.insert(heights.begin(), 0); // 解决原序列降序时,栈第一个元素没有left
        heights.push_back(0); // 原序列升序,最后一个没有right
        int result = 0; 
        st.push(0);
        for (int i = 1; i < heights.size(); i++) {
            while (heights[i] < heights[st.top()]) {
                int mid = st.top();
                st.pop();
                int w = i - st.top() - 1;
                int h = heights[mid];
                result = max(result, w * h); 
            }
            st.push(i);
        }
        return result;
    }
};