简单暴力的思路,两个for循环解决问题,时间复杂度n^2
public class LeetCode84 {
public static int largestRectangleArea2(int[] heights) {
int max = 0;
for (int i = 0; i < heights.length; i++){
int min = Integer.MAX_VALUE;
for (int j = i; j < heights.length; j++){
min = Math.min(heights[j], min);
max = Math.max(max, min * (j - i + 1));
}
}
return max;
}
}
优化后的代码
class Solution {
public int largestRectangleArea(int[] heights) {
int res = 0;
Deque<Integer> stack = new ArrayDeque<>();
int[] new_heights = new int[heights.length + 2];
for (int i = 1; i < heights.length + 1; i++) new_heights[i] = heights[i - 1];
//System.out.println(Arrays.toString(new_heights));
for (int i = 0; i < new_heights.length; i++) {
//System.out.println(stack.toString());
while (!stack.isEmpty() && new_heights[stack.peek()] > new_heights[i]) {
int cur = stack.pop();
res = Math.max(res, (i - stack.peek() - 1) * new_heights[cur]);
}
stack.push(i);
}
return res;
}
}