[LeetCode]Largest Rectangle in Histogram

本文介绍了一种求解最大直方图面积的问题,并提供了一个使用栈实现的高效算法,该算法的时间复杂度为O(n),优于常规做法的O(n^2)。通过巧妙地利用栈的数据结构特性,该算法能够快速找到每个柱状区域的最大矩形面积。

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

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.

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

 

常规的做法就是对每个点计算最大的面积值,最后得到总体的最大值,这样做的时间复杂度是O(n^2)。

巧妙利用stack的性质,可以将时间复杂度降为O(n)。参考这篇博文

 1 class Solution {
 2 public:
 3     int largestRectangleArea(vector<int>& height) {
 4         int result=0;
 5         height.push_back(0);
 6         stack<int> mystack;
 7         for(int i=0;i<height.size();i++)
 8         {
 9             if(mystack.empty() || height[mystack.top()]<=height[i])
10             {
11                 mystack.push(i);
12             }
13             else
14             {
15                 int index = mystack.top();
16                 mystack.pop();
17                 int area = height[index]*(mystack.empty()?i:(i-mystack.top()-1));
18                 result = max(result,area);
19                 i--;
20             }
21         }
22         return result;
23     }
24 };

 

转载于:https://www.cnblogs.com/Sean-le/p/4746077.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值