Created
September 25, 2016 14:10
-
-
Save eclipselu/7f1fd13a05284d1ae8c2c4884c20f5be to your computer and use it in GitHub Desktop.
Largest Rectangle in Histogram
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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