要求:构造矩形
思路:暴力是在每个矩形处找以它为高度的最大面积,即找它左右第一个比它矮的之间的。单调栈:遇到比栈顶矮的就能计算栈顶了,高的就入栈
class Solution {
public:
int largestRectangleArea(vector<int> &heights) {
unsigned long size = heights.size();
if (size == 1) {
return heights[0];
}
int res = 0;
stack<int> stk;
for (int i = 0; i < size; ++i) {
while (!stk.empty() && heights[stk.top()] > heights[i]) {
int length = heights[stk.top()];
stk.pop();
int weight = i;
if (!stk.empty()) {
weight = i - stk.top() - 1;
}
res = max(res, length * weight);
}
stk.push(i);
}
while (!stk.empty()) {
int length = heights[stk.top()];
stk.pop();
int weight = size;//尾部加0
if (!stk.empty()) {
weight = size - stk.top() - 1;//连续两个相等的在这里计算
}
res = max(res, length * weight);
}
return res;
}
};