import java.util.*;
public class Solution {
public static int largestRectangle(ArrayList < Integer > heights) {
int len = heights.size();
int rb[] = new int [len];
Stack<Integer> st = new Stack<>();
for (int i = len-1; i >= 0; i--) {
int cur = heights.get(i);
while (!st.isEmpty() && heights.get(st.peek()) >= cur)
st.pop();
if (st.isEmpty() == true)
rb[i] = len;
else
rb[i] = st.peek();
st.push(i);
}
int lb[] = new int [len];
st = new Stack<>();
for (int i = 0; i < len; i++) {
int cur = heights.get(i);
while (!st.isEmpty() && heights.get(st.peek()) >= cur)
st.pop();
if (st.isEmpty() == true)
lb[i] = -1;
else
lb[i] = st.peek();
st.push(i);
}
int maxArea = 0;
for (int i = 0; i < len; i++) {
int width = rb[i] - lb[i] - 1;
int curArea = width * heights.get(i);
maxArea = Math.max(maxArea, curArea);
}
return maxArea;
}
}