一.题目描述
示意图
1.可以直接暴力做题,从左到右遍历每一列上的每一个,但超时不多赘述
#include<iostream>
using namespace std;
const int maxsize = 1e5 + 3;
int arr[maxsize];
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> arr[i];
}
int ans = 0; int res = 0;
for (int i = 1; i <= n; i++)
{
ans = 0;
int j = i;
int now = arr[i];
ans = arr[i];
while (now <= arr[i + 1]&&i<=n)
{
ans += now;
i++;
}
i = j;
while (now<=arr[i-1]&&i>=1)
{
ans += now;
i--;
}
if (res<=ans)
{
res = ans;
}
i = j;
}
cout << res;
}
2.单调栈
通过先读取,当栈顶的元素的值小与当前的元素,那么该元素压入栈中;当栈顶的值小于当前的值,那么弹出栈顶的值并计算最大面积(一直判断弹出,直到该元素大与栈顶的值),当空栈时,即为栈顶的值为0,继续判断
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int> st;
heights.push_back(0);//结尾虚拟柱子高度0
int size = heights.size();
int res = 0;
for (int i = 0; i < size; ++i)
{
while (!st.empty() && heights[st.top()] >= heights[i])
{
int val = st.top();
st.pop();
if (!st.empty())
res = max(res, heights[val] * (i - st.top() - 1));
else
{
res = max(res, heights[val] * i);
}
//宽度不包含当前元素
}
st.push(i);
}
return res;
}
};