Skip to content

Instantly share code, notes, and snippets.

@eclipselu
Created September 25, 2016 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eclipselu/7f1fd13a05284d1ae8c2c4884c20f5be to your computer and use it in GitHub Desktop.
Save eclipselu/7f1fd13a05284d1ae8c2c4884c20f5be to your computer and use it in GitHub Desktop.
Largest Rectangle in Histogram
class Solution {
public:
/**
* @param height: A list of integer
* @return: The area of largest rectangle in the histogram
*/
int largestRectangleArea(vector<int> &height) {
stack<int> heightSt;
stack<int> indexSt; // start index
int maxArea = 0;
height.push_back(0);
for (int i = 0; i < height.size(); ++i) {
int h = height[i];
if (i == 0 || h > heightSt.top()) {
heightSt.push(h);
indexSt.push(i);
} else {
// h <= heightSt.top()
int startIndex = i;
while (!heightSt.empty() && h <= heightSt.top()) {
startIndex = indexSt.top();
int currentHeight = heightSt.top();
int currentArea = (i - startIndex) * currentHeight;
maxArea = max(maxArea, currentArea);
heightSt.pop();
indexSt.pop();
}
heightSt.push(h);
indexSt.push(startIndex);
}
}
return maxArea;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment