84. 柱状图中最大的矩形
这道题是单调栈递减的应用,但是依旧有细节需要注意,那就是如果给定数组是单调递增,或者单调递减时,无法计算出面积。因此,在这个基础上需要在数组的两边分别添加元素0,来保证一定可以计算出结果,代码如下:
public int largestRectangleArea(int[] heights) {
int[] dp = new int[heights.length+2];
for(int i=1;i<dp.length-1;i++){
dp[i] = heights[i-1];
}
Stack<Integer> st = new Stack();
st.push(0);
int re = 0;
int w = 0;
int h = 0;
int tool;
for(int i=0;i<dp.length;i++){
if(dp[i]>=dp[st.peek()])st.push(i);
else{
while(!st.isEmpty()&&dp[i]<dp[st.peek()]){
tool = dp[st.pop()];
if(!st.isEmpty()){
h = tool;
w = i-st.peek()-1;
if(re<h*w)re = h*w;
}
}
st.push(i);
}
}
return re;
}
坚持六十天了,嗯 真不错