Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
public int largestRectangleArea(int[] height) {
//参数合法性校验
if(height == null || height.length <= 0){
return 0;
}
//辅助数据结构,递增栈
Stack<Integer> stack = new Stack<>();
//用于记录弹出元素对应的直方图对应的面积
int sum = 0;
//用于记录连续弹出的直方图的个数
int count = 0;
//循环处理数组
for(int i = 0 ; i < height.length ; i++){
//处理当前数组元素为数组首元素、当前数组元素大于等于栈顶元素的情况
if(stack.isEmpty() || stack.peek() <= height[i]){
stack.push(height[i]);
}else{
//用于处理当前数组元素小于栈顶元素的情况
while(stack.size() !=0 && stack.peek() > height[i]){
//弹出栈顶元素
int top = stack.pop();
//记录连续弹出元素的个数
count++;
//弹出的栈顶元素(可能是连续多个)所能构成的最大面积
sum = Math.max(count*top,sum);
}
//将当前元素作为替补取代之前弹出的元素以保持栈元素的递增
while(count != 0){
stack.push(height[i]);
count--;
}
//最后将当前元素压入栈中
stack.push(height[i]);
}
}
//找出递增栈对应的每个组合的最大值,并与max进行比较,取最后的最大值为结果返回
count = 0;
while(stack.size() != 0){
int top = stack.pop();
count++;
sum = Math.max(sum,top*count);
}
return sum;
}