#include <algorithm>
#include <iostream>
#include <stack>
#include <vector>
int solution(int n, std::vector<int> A) {
// Edit your code here
int ans = 0;
std::stack<int> st;//单调栈记录
A.push_back(0);
A.insert(A.begin(), 0);
for(int i = 0; i < A.size(); i++){
while (!st.empty() && A[i] < A[st.top()]) {
int cur = A[st.top()];
st.pop();
int left = st.top() + 1;
int right = i - 1;
ans = std::max(ans, cur * (right - left + 1));
}
st.push(i);
}
return ans;
}
int main() {
// Add your test cases here
std::vector<int> A_case1 = std::vector<int>{1, 2, 3, 4, 5};
std::cout << (solution(5, A_case1) == 9) << std::endl;
return 0;
}
其中做了一个优化在数组的两边插入了两个0防止边界条件的判断。
用单调栈记录变大的高度,当高度小于当前记录的最大高度时,计算最大高度能组成的矩形面积。这个矩形的长是当前栈中记录的最大值,他的左边界是当前栈顶元素的前一个元素加一,他的右边界为i-1.即可计算当前面积。寻找出最大的面积。
其解释可以看程序员卡尔链接:单调栈,又一次经典来袭! LeetCode:84.柱状图中最大的矩形_哔哩哔哩_bilibili