您的位置:首页 > 其它

[leetcode刷题系列]Largest Rectangle in Histogram

2013-08-08 21:01 381 查看
经典题了, 利用stack优化, O(n)

const int MAXN = 1e6 + 10;

int n;
int pleft[MAXN], pright[MAXN];
stack<int> stk;

class Solution {

public:
int largestRectangleArea(vector<int> &height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
n = height.size();
//left
for(int i = n - 1; i >= 0; -- i){
while(!stk.empty()){
int now = stk.top();
if(height[i] < height[now]){
pleft[now] = i;
stk.pop();
}else break;
}
stk.push(i);
}
while(!stk.empty()){
pleft[stk.top()] = -1;
stk.pop();
}
// right
for(int i = 0; i < n; ++ i){
while(!stk.empty())
if(height[i] < height[stk.top()]){
pright[stk.top()] = i;
stk.pop();
}else break;
stk.push(i);
}
while(!stk.empty()){
pright[stk.top()] = n;
stk.pop();
}
int ans = 0;
for(int i = 0; i < n; ++ i)
ans = max(ans, height[i] *(pright[i] - pleft[i] - 1));
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: