84. 柱状图中最大的矩形
class Solution {
public int largestRectangleArea(int[] heights) {
int res=0;
// 数组扩容,在头和尾各加入一个元素
int [] newHeights = new int[heights.length + 2];
newHeights[0] = 0;
newHeights[newHeights.length - 1] = 0;
for (int index = 0; index < heights.length; index++){
newHeights[index + 1] = heights[index];
}
heights = newHeights;
Stack<Integer> st = new Stack<>();
st.push(0);
for(int i=1;i<heights.length;i++){
if(heights[i] > heights[st.peek()]){
st.push(i);
}
else if(heights[i]==heights[st.peek()]){
st.pop();
st.push(i);
}
else{
while(!st.isEmpty() && heights[i]<heights[st.peek()]){
int mid = st.pop();
if(!st.isEmpty()){
int w = i-st.peek()-1;
int h = heights[mid];
res = Math.max(res, h*w);
}
}
st.push(i);
}
}
return res;
}
}