前提知识:单调栈基础题-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;
}



















