84. Largest Rectangle in Histogram
暴力解法:
class Solution {
public int largestRectangleArea(int[] heights) {
int n=heights.length;
int maxArea=0;
for(int i=0;i<n;i++)
{
int min_height=heights[i];
for(int j=i;j>=0;j--)
{
min_height=Math.min(min_height,heights[j]);
maxArea=Math.max(maxArea,(i-j+1)*min_height);
}
}
return maxArea;
}
}
解法二:单调栈
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> stack=new Stack<>();
int maxArea=0,n=heights.length;
for(int i=0;i<=n;i++)
{
while(!stack.isEmpty() && (i==n || heights[stack.peek()]>heights[i]) )
{
int index=stack.pop();
int h=heights[index];
int w=stack.isEmpty()?i:i-stack.peek()-1;
maxArea=Math.max(maxArea,h*w);
}
stack.push(i);
}
return maxArea;
}
}