Skip to content

Instantly share code, notes, and snippets.

@songouyang
Created December 2, 2017 08:44
Show Gist options
  • Save songouyang/9f6cad499dcc18e381b6584b03b091c1 to your computer and use it in GitHub Desktop.
Save songouyang/9f6cad499dcc18e381b6584b03b091c1 to your computer and use it in GitHub Desktop.
84. Largest Rectangle in Histogram
class Solution {
public:
int largestRectangleArea(vector<int> &heights) {
stack<int> s;
int max_size = 0;
heights.push_back(-1);
for (int i = 0; i < heights.size(); ++i) {
while (!s.empty() and heights[i] < heights[s.top()]) {
int tmp = s.top();
int h = heights[tmp];
s.pop();
int w = s.empty() ? i : i - s.top() - 1;
max_size = max(max_size, h * w);
}
s.push(i);
}
return max_size;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment