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