LeetCode 84.柱状图中最大的矩形
代码如下(Java):暴力解法
class Solution {
public int largestRectangleArea(int[] heights) {
int length = heights.length;
int[] minLeftIndex = new int[length];
int[] minRightIndex = new int[length];
minLeftIndex[0] = -1;
for(int i = 1; i < length; i++){
int t = i - 1;
while(t >= 0 && heights[t] >= heights[i]) t = minLeftIndex[t];
minLeftIndex[i] = t;
}
minRightIndex[length-1] = length;
for(int i = length - 2; i >= 0; i--){
int t = i + 1;
while(t < length && heights[t] >= heights[i]) t = minRightIndex[t];
minRightIndex[i] = t;
}
int result = 0;
for(int i = 0; i < length; i++){
int sum = heights[i] * (minRightIndex[i] - minLeftIndex[i] - 1);
result = Math.max(sum, result);
}
return result;
}
}