LeetCode Largest Rectangle in Histogram(栈的使用)

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.


Above is a histogram where width of each bar is 1, given height =[2,1,5,6,2,3].


The largest rectangle is shown in the shaded area, which has area =10 unit.

For example,
Given height = [2,1,5,6,2,3],
return 10.

题意 :给出一些条状构成的直方图,求其最大的矩形面积
思路:如果条状图是单调递增的,其最大面积为max{height[I] * (len - I)},其中heigh[I]表示数组height的第i个值 ,len表示数组的长度,i表示对应的下标
          因此,首先将数值入栈,当出现当前值比先前值小,将栈中数据出栈,直到栈顶的值比当前值小。
代码如下:

class Solution {
    public int largestRectangleArea(int[] height)
    {
        Stack<Integer> stack = new Stack<Integer>();

        int ans = 0;

        for (int i = 0; i < height.length; i++)
        {
            if (stack.empty() || stack.peek() < height[i])
            {
                stack.push(height[i]);
            }
            else
            {
                int cnt = 1;

                while (!stack.empty() && stack.peek() > height[i])
                {
                    ans = Math.max(ans, stack.pop() * cnt);
                    cnt++;
                }

                while (cnt-- > 0)
                {
                    stack.push(height[i]);
                }
            }
        }

        int cnt = 1;
        while (!stack.empty())
        {
            ans = Math.max(ans, stack.pop() * cnt);
            cnt++;
        }

        return ans;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值