LeetCode训练营之栈与队列

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;
	    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值