题目链接: Largest Rectangle in a Histogram
大致题意
给定一个宽度为 n n n的图形, 由 n n n个宽度为1, 高度为 h i h_i hi的矩形组成.
要求计算出最大矩形的面积.
解题思路
思维
首先我们最终选取出的大矩形高度一定为某个 h i h_i hi.
我们考虑到对于完全包含第 i i i个小矩形而言的答案, 相当于需要在 i i i左侧找到小于 h i h_i hi的点, 则记录 i i i位置可以向左延伸 l i l_i li, 右侧同理记录出 r i r_i ri.
这样答案为 r e s = m a x ( ( r i − l i − 1 ) × h i ) res = max({ (r_i - l_i - 1) \times h_i }) res=max((ri−li−1)×hi).
单调栈
由于我们需要计算出某个位置左侧第一个小于 h i h_i hi的点, 因此可以采用单调栈维护.
AC代码
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
using namespace std;
typedef long long ll;
const int N = 1E5 + 10;
int a[N], l[N], r[N];
int main()
{
int n;
while (scanf("%d", &n), n) {
rep(i, n) scanf("%d", &a[i]);
stack<int> st;
rep(i, n) {
while (!st.empty() and a[st.top()] >= a[i]) st.pop();
l[i] = st.empty() ? i : i - st.top();
st.push(i);
}
st = stack<int>();
for (int i = n; i >= 1; --i) {
while (!st.empty() and a[st.top()] >= a[i]) st.pop();
r[i] = st.empty() ? n - i + 1 : st.top() - i;
st.push(i);
}
ll res = 0;
rep(i, n) res = max(res, 1ll * (r[i] + l[i] - 1) * a[i]);
printf("%lld\n", res);
}
return 0;
}