# 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.

因此，首先将数值入栈，当出现当前值比先前值小，将栈中数据出栈，直到栈顶的值比当前值小。

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;
}
}


• 本文已收录于以下专栏：

## LeetCode Largest Rectangle in Histogram

• 2015年06月22日 23:25
• 2.67MB
• 下载

## LeetCode 84 Largest Rectangle in Histogram (单调栈)

LeetCode 84 Largest Rectangle in Histogram (单调栈)

## [Leetcode]Largest Rectangle in Histogram - 非递减栈(递增及相等)

Given n non-negative integers representing the histogram's bar height where the width of each bar is...

## [leetcode] 84. Largest Rectangle in Histogram

Given n non-negative integers representing the histogram's bar height where the width of each bar i...

## leetcode No84. Largest Rectangle in Histogram

Question： Given n non-negative integers representing the histogram's bar height where the width o...

## LeetCode-84.Largest Rectangle in Histogram

Given n non-negative integers representing the histogram's bar height where the width of each bar is...

## leetcode84: Largest Rectangle in Histogram

84. Largest Rectangle in Histogram height的内容是 [5,6,7,8,3]，特点是除了最后一个，前面全部保持递增，且最后一个立柱的高度小于前面所有立柱高度。对...

## Largest Rectangle in Histogram （直方图中最大面积） 【leetcode】

举报原因： 您举报文章：LeetCode Largest Rectangle in Histogram(栈的使用) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)