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.
Example:
Input: [2,1,5,6,2,3]
Output: 10
找出最大的矩形,并返回其面积:
方法一:暴力搜索对其所有结果进行遍历。最终超时。
public int largestRectangleArea(int[] heights) {
int n = heights.length;
int[][]res = new int[n][n];
for(int i=0;i<n;i++) {
int min = heights[i];
for(int j=i;j<n;j++) {
min = Math.min(min, heights[j]);
res[i][j] = min*(j-i+1);
if(i==0 && j==0) {
continue;
}else {
if (i > 0) {
res[i][j] = Math.max(res[i][j], res[i - 1][j]);
}
if(j>0) {
res[i][j] =Math.max(res[i][j], res[i][j-1]);
}
}
}
}
return n==0 ?0:res[n-1][n-1];
}
方法二:优化方法:找出每一个局部波峰值,当前的数字大于后面的数字,只计算出这些波峰值之间的最大值面积,进行比较
public int largestRectangleArea(int[] heights) {
int max = 0;
for (int i = 0; i < heights.length; i++) {
// 调过非波峰值的结果
if (i + 1 < heights.length && heights[i] <= heights[i + 1]) {
continue;
}
int height = heights[i];
for (int j = i; j >= 0; j--) {
height = Math.min(height, heights[j]);
max = Math.max(max, height * (i - j + 1));
}
}
return max;
}