Created
October 22, 2016 02:52
-
-
Save kartikkukreja/402d322b3d7f967ccf357dd6cc304537 to your computer and use it in GitHub Desktop.
Largest rectangle in a histogram with precomputation
This file contains 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
int largestRectangleArea(vector<int> &A) { | |
int n = A.size(); | |
vector<int> posLeft(n); | |
stack<int> S; | |
for (int i = 0; i < n; i++) { | |
while (!S.empty() && A[S.top()] >= A[i]) | |
S.pop(); | |
posLeft[i] = S.empty() ? 0 : S.top() + 1; | |
S.push(i); | |
} | |
vector<int> posRight(n); | |
while (!S.empty()) S.pop(); | |
for (int i = n-1; i >= 0; i--) { | |
while (!S.empty() && A[S.top()] >= A[i]) | |
S.pop(); | |
posRight[i] = S.empty() ? n-1 : S.top() - 1; | |
S.push(i); | |
} | |
int maxArea = 0; | |
for (int i = 0; i < n; i++) | |
maxArea = max(maxArea, (posRight[i] - posLeft[i] + 1) * A[i]); | |
return maxArea; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment