代码随想录第六十天
Leetcode 84. 柱状图中最大的矩形
题目链接: 柱状图中最大的矩形
自己的思路:没想到!!
正确思路:和接雨水类似,只是需要左右补0!!!
代码:
class Solution {
public int largestRectangleArea(int[] height) {
int[] heights = new int[height.length+2];
//左右两边补0
for (int i=0;i<height.length;i++){
heights[i+1] = height[i];
}
int res = 0;
LinkedList<Integer> st = new LinkedList<>();
st.addFirst(0);
for (int i =1;i<heights.length;i++){
//找左边和右边分别比它小的数
if (heights[i]>=heights[st.getFirst()]) st.addFirst(i);
else{
while(!st.isEmpty()&&heights[i]<heights[st.getFirst()]){
int temp = st.removeFirst();
int w = i-st.getFirst()-1;
int h = heights[temp];
int s = w*h;
res = Math.max(s,res);
}
st.addFirst(i);
}
}
return res;
}
}