链接:LintCode 炼码 - ChatGPT!更高效的学习体验!
题解:这是一个单调递增栈,弹出的元素保证,从当前位置向后扫,能构成矩形
九章算法 - 帮助更多程序员找到好工作,硅谷顶尖IT企业工程师实时在线授课为你传授面试技巧
class Solution {
public:
/**
* @param heights: A list of integer
* @return: The area of largest rectangle in the histogram
*/
int largestRectangleArea(vector<int> &heights) {
// write your code here
if (heights.size() <= 0) {
return 0;
}
std::stack<int> sta;
int result = 0;
for (int i = 0; i <= heights.size(); ++i) {
int cur_height = i == heights.size() ? -1 : heights[i];
while (!sta.empty() && cur_height <= heights[sta.top()]) {
int top = sta.top();
sta.pop();
int h = heights[top];
int w = sta.empty() ? i : i - sta.top() - 1;
result = max(result, h * w);
}
sta.push(i);
}
return result;
}
};