Leetcode DAY 60:柱状图中最大的矩形Largest Rectangle in Histogram

Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

思路:

需要找到中间柱子mid左右两边第一小的柱子left、right,选取mid的高的那个作为矩形的高 h   , left和right中间的部分作为宽w 也就是 left - right - 1

实现中遇到的问题:

输入:【2,4】 却输出了 0 而不是 4    通过分析得知  没有对柱子的边界进行处理  因此需要对heights数组的头尾分别插入0

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        stack<int> st;
        heights.insert(heights.begin(), 0);
        heights.push_back(0);
        st.push(0);
        int res = 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 right = i;
                        int left = st.top();
                        int h = heights[mid];
                        int w = right - left - 1;
                        res = max(res, h * w);
                    }
                }
                st.push(i);
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_44189622/article/details/129437549