直方图的最大长方形面积

前提知识:单调栈基础题-CSDN博客    子数组的最大值-CSDN博客

题目描述:

给定一个非负数(0和正数),代表直方图,返回直方图的最大长方形面积,比如,arr = {3, 2, 4, 2, 5},那么直方图就是下面这个样子的,最大的长方形面积为图中阴影部分面积,为2*5 = 10。

way:

遍历arr数组,以当前遍历到的数组元素作为它所在的长方形中的最小的高,向它的两边往外扩,那么当遇到左边的最近的比它小的元素和右边离它最近且比它小的元素时,停止扩张,中间的区域都是能以它作为最小的高的长条,计算长方形面积 = 当前最小高 * 区域长度,取max。

#include<iostream>
#include<vector>
#include<stack>
using namespace std;

int largestRectangleArea(vector<int> arr)
{
	int N = arr.size();
	stack<int>st;
	int nMax = INT_MIN;
	for (int i = 0; i < N; i++)
	{
		while (!st.empty() && arr[i] <= arr[st.top()])
		{
			int topIndex = st.top();
			st.pop();
			int leftIndex = st.empty() ? -1 : st.top();
			int rightIndex = i;
			nMax = max(nMax, arr[topIndex] * (rightIndex - 1 - leftIndex));
		}
		st.push(i);
	}
	while (!st.empty())
	{
		int topIndex = st.top();
		st.pop();
		int leftIndex = st.empty() ? -1 : st.top();
		int rightIndex = N;
        // (rightIndex-1)-(leftIndex+1)+1 
		nMax = max(nMax, arr[topIndex] * (rightIndex - 1 - leftIndex));
	}
	return nMax;
}


int main()
{
	vector<int> arr = { 3,2,4,2,5 };
	int nMax = largestRectangleArea(arr);
	cout << nMax << endl;
	return 0;
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值