题目编号84:给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。求在该柱状图中,能够勾勒出来的矩形的最大面积。

思路:直接遍历每一个柱子,求出最大的面积
public static int largestRectangleArea(int[] heights) {
//数组长度为空
if (heights == null || heights.length == 0){
return 0;
}
int len = heights.length;
int maxArea = 0;
for (int i=0; i<len; i++){
//遍历每一个元素
int left = i;
while (left>0 && heights[left-1] >= heights[i]){
left--;
}
int right = i;
while (right<len-1 && heights[right+1] >= heights[i]){
right++;
}
int area = (right - left + 1) * heights[i];
maxArea = Math.max(maxArea,area);
}
return maxArea;
}
2、用辅助栈来求解
思路:遍历数组,当前元素大于栈顶元素时,入栈;当前元素小于栈顶元素时,则说明栈顶元素已经找到计算最大面积的左右边界。
public static int largestRectangleArea2(int[] heights) {
//特殊情况
if (heights == null) return 0;
int len = heights.length;
if (len == 0) return 0;
if (len == 1) return heights[0];
int[] nums = new int[len + 2];
System.arraycopy(heights,0,nums,1,len);
len = len + 2;
Stack<Integer> stack = new Stack<>();
stack.add(0);//哨兵
int max = 0;
for (int i=1; i<len; i++){
while (nums[i] < nums[stack.peek()]){
int curHeight = nums[stack.pop()];
int curWidth = i - stack.peek() - 1;
max = Math.max(max,curHeight * curWidth);
}
stack.push(i);
}
return max;
}