leetcode || 84、Largest Rectangle in Histogram

本文介绍了一种在柱状图中寻找最大矩形面积的有效算法。通过使用栈来存储高度单调递增的索引,该算法能在O(N)的时间复杂度内解决问题。文章对比了暴力破解方法,并详细解析了栈实现的思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

problem:

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.

For example,
Given height = [2,1,5,6,2,3],
return 10.

Hide Tags
  Array Stack
题意:在一个数组表示的柱状图中寻找最大的矩形面积

thinking:

(1)最先想到暴力破解,两次遍历,记录最大面积。提交发现超时了。

(2)http://blog.youkuaiyun.com/doc_sgl/article/details/11805519  给出了一个用stack实现的O(n)算法,很高效。

大致思想是:stack里面只存放height单调递增的索引,最大矩形最可能出现在这几列中

code:

暴力破解: 提交 TLE

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        int n=height.size();
        if(n==0)
            return 0;
        if(n<2)
            return height[0];
        int area=height[0];
        int index=0;
        for(int i=1;i<n;i++)
        {
            index=height[i];
            for(int j=i;j>=0;j--)
            {
                index=min(index,height[j]);
                area=max(area,index*(i-j+1));
            }
        }
        return area;
    }
};
借助stack  O(N)算法

class Solution {
public:
    int Max(int a, int b){return a > b ? a : b;}
    int largestRectangleArea(vector<int> &height) {
    	height.push_back(0);
        stack<int> stk;
        int i = 0;
        int maxArea = 0;
        while(i < height.size()){
            if(stk.empty() || height[stk.top()] <= height[i]){
                stk.push(i++);
            }else {
                int t = stk.top();
				stk.pop();
                maxArea = Max(maxArea, height[t] * (stk.empty() ? i : i - stk.top() - 1));
            }
        }
        return maxArea;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值