Skip to content

Instantly share code, notes, and snippets.

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 kartikkukreja/402d322b3d7f967ccf357dd6cc304537 to your computer and use it in GitHub Desktop.
Save kartikkukreja/402d322b3d7f967ccf357dd6cc304537 to your computer and use it in GitHub Desktop.
Largest rectangle in a histogram with precomputation
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