代码随想录算法训练营第六十天

第一题、柱状图中最大的矩形 力扣题目链接

class Solution {
public:
    int largestRectangleArea(vector& heights) {
        int result = 0;
        stack st;
        heights.insert(heights.begin(), 0);
        heights.push_back(0);
        st.push(0);

        for(int i=1; i < heights.size(); i++){
            if(heights[i] >= heights[st.top()]) 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, h * w);
                    }
                }
                st.push(i);
            }
        }
        return result;
    }
};

60天完结撒花~

你可能感兴趣的:(算法,leetcode,c++)