[LeetCode] Largest Rectangle in Histogram 直方图中最大的矩形

题目描述:

Given *n* non-negative integers representing the histogram's bar height 
where the width of each bar is 1, find the area of largest rectangle in the
 histogram.
Above is a histogram where width of each bar is 1, given height = `[2,1,5,6,2,3]`.
The largest rectangle is shown in the shaded area, which has area = `10` unit
Example:
input: [2,1,5,6,2,3]
Output: 10

解题思路:
本题要求我们求出直方图中最大的矩形面积。仔细观察分析可以知道,关键是找到直方图中最大矩形的长和高。

那么如何得到直方图中最大矩形呢?一个想法是对于直方图中的每一个局部峰值,都向前遍历,算出其最大的公共矩形。

而为了寻找直方图中的局部峰值,我们可以借由stack来实现:即将直方图的高度依次入栈,只要当前高度小于栈顶,则栈顶为一个局部峰值。

解法如下:

int largestRectangleArea(vector<int>& heights) {
        stack<int> s;
        //insert 0 in origial stack
        s.push(0);
        
        int res = 0;
        
        for(int i = 0; i < heights.size();){
            //if current height larger than s.top, 
            //push into stack
            if(s.empty()||heights[i]>=heights[s.top()]){
                s.push(i);
                i++;
            }
            else{
                //else, find the current largest rectangle
                int h = heights[s.top()];
                s.pop();
                
                int w = (!s.empty())?i-s.top()-1:i;
                
                res = max(res,h*w);
            }
        }
        return res;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容