单调栈的妙用
class Solution {
public int largestRectangleArea(int[] heights) {
if(heights==null||heights.length == 0) return 0;
int left = 0;
int right = heights.length - 1;
int maxRet = 0;
int step = 0;
while(left<heights.length){
int minHeight = Integer.MAX_VALUE;
for(int i=left;i<=right;i++){
minHeight = Math.min(minHeight,heights[i]);
int tmp = (i - left + 1) * minHeight;
if(tmp > maxRet) maxRet = tmp;
}
left++;
}
return maxRet;
}
}
public class Solution {
public int largestRectangleArea(int[] heights) {
if(heights==null||heights.length == 0) return 0;
Stack<Integer> stack = new Stack<>();
stack.push(-1);
int maxRet = 0;
for(int i=0;i<heights.length;i++){
while(stack.peek()!=-1 && heights[stack.peek()]>=heights[i]){
int p = stack.pop();
int square = (i - stack.peek() - 1) * heights[p];
if(square > maxRet) maxRet = square;
}
stack.push(i);
}
while(stack.peek()!=-1){
int p = stack.pop();
int square = (heights.length - stack.peek() - 1) * heights[p];
if(square > maxRet) maxRet = square;
}
return maxRet;
}
}