题目:
给定一个数组heights,长度为n,height[i]是在第i点的高度,那么height[i]表示的直方图,能够形成的最大矩形是多少?
1.每个直方图宽度都为1
2.直方图都是相邻的
3.如果不能形成矩形,返回0即可
4.保证返回的结果不会超过2^31-1
样式输入:3 4 7 8 1 2 |
样式输出:14 |
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<stack>
#include<string>
#include<queue>
#include<algorithm>
using namespace std;
int main()
{
string s;
int num[10000] = { 0 };
int cnt[10000] = { 0 };
int count = 1;
getline(cin, s);
s += ' ';
int sum = 0;
for (int i = 0; i < s.size(); i++)
{
if (s[i] == ' ')
{
num[count++] = sum;
sum = 0;
}
else
{
sum = sum * 10 + s[i] - '0';
}
} //将字符串中的数字提取出来
int Max = 0;
num[0] = 0;
num[count] = 0;
stack<int> st;
for (int i = 0; i <= count; i++)
{
while (!st.empty()&&num[st.top()]>num[i])
{
int mid = st.top(); //当前要计算的矩形的基准下标
st.pop();
int left = st.top(); //基准左边第一个比他小的柱状图的下标
//i为基准右边第一个比他小的柱状图的下标
Max = max(Max, num[mid] * (i - left - 1));//比较大小
}
st.push(i);
}
cout << Max;
return 0;
}