84. Largest Rectangle in Histogram

1 min read
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> st = new Stack<>();
int res = 0;
for(int i=0; i<heights.length; i++){
while(!st.isEmpty() && heights[st.peek()] >= heights[i]){
int top = st.pop();
int pse = st.isEmpty()?-1:st.peek();
res = Math.max(res, heights[top]*(i-pse-1));
}
st.push(i);
}
while(!st.isEmpty()){
int top = st.pop();
int nse=heights.length, pse = st.isEmpty()?-1:st.peek();
res = Math.max(res, heights[top]*(nse-pse-1));
}
return res;
}
}
0
Subscribe to my newsletter
Read articles from Mohd Shakeel directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
