#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
int maxArea(std::vector<int>& arr) {
int n = arr.size();
std::vector<int> left(n), right(n, n);
std::stack<int> st;
for (int i = 0; i < n; ++i) {
while (!st.empty() && arr[st.top()] >= arr[i]) {
right[st.top()] = i;
st.pop();
}
left[i] = (st.empty() ? -1 : st.top());
st.push(i);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans = std::max(ans, (right[i] - left[i] - 1) * arr[i]);
}
return ans;
}
int maxAreaV2(std::vector<int>& arr) {
arr.push_back(0);
int n = arr.size();
int ans = 0;
std::stack<int> st;
for (int i = 0; i < n; ++i) {
while (!st.empty() && arr[st.top()] > arr[i]) {
int top = st.top();
int h = arr[top];
int w = i - top;
ans = std::max(ans, h * w);
st.pop();
if (st.empty()) {
break;
}
}
st.push(i);
}
return ans;
}
int main() {
std::vector<int> arr{ 4, 1, 2, 3, 15, 6};
int res = maxAreaV2(arr);
printf("%d\n", res);
return 1;
}
柱状图中最大的矩形
于 2023-04-25 17:12:43 首次发布