# 单调栈的应用(leetcode 85 maximal_Recetangle leetcode 84 largest_rectangle_in_histogram)

3 5 10 12 7 8 20


class R {
public int x;
public int y;

public R(int x, int y) {
this.x = x;
this.y = y;
}
}

public int largestRectangleArea(int[] height) {
if(height.length==0)
return 0;

Stack<R> stack = new Stack<>();
//维护一个单调递zeng的单调栈
int pos = 0;
int max = 0;
while (pos < height.length) {
\\ R tr = stack.peek();
int len = 1;
while (!stack.isEmpty() && (stack.peek().x > height[pos])) {
len += stack.peek().y;
max = Math.max((len - 1) * stack.peek().x, max);
stack.pop();
}
stack.push(new R(height[pos++], len));
}
int len = 0;
while (!stack.isEmpty()) {
len += stack.peek().y;
max = Math.max(max, len * stack.pop().x);
}
\\   System.out.print(max);
return max;
}

leetcode最大矩形面积

AC代码如下：

    class R {
int x;
int y;
public R(int x, int y) {
this.x = x;
this.y = y;
}
}
int dp[][];
public int maximalRectangle(char[][] matrix) {
if (matrix.length == 0)
return 0;
int len1 = matrix.length;
int len2 = matrix[0].length;
dp = new int[len1][len2];
for (int i = 0; i < len1; i++) {
for (int j = 0; j < len2; j++) {
dp[i][j] = 0;
}
}
for (int i = 0; i < len2; i++) {
dp[0][i] = matrix[0][i] == '1' ? 1 : 0;
}
Stack<R> stack = new Stack<>();
int a[] = new int[len2];
a[0] = matrix[0][0] == '1' ? 1 : 0;
int max = a[0];
for (int i = 1; i < len2; i++) {
if (matrix[0][i] == '1') {
a[i] = a[i - 1] + 1;
max = Math.max(max, a[i]);
} else {
a[i] = 0;
}
}
for (int i = 1; i < len1; i++) {
for (int j = 0; j < len2; j++) {
if (matrix[i][j] == '1') {
dp[i][j] = dp[i - 1][j] + 1;
}
int len = 1;
while (!stack.isEmpty() && (stack.peek().x > dp[i][j])) {
len = len + stack.peek().y;
max = Math.max(max, (len - 1) * stack.peek().x);
stack.pop();
}
stack.push(new R(dp[i][j], len));
}
int slen = 0;
while (!stack.isEmpty()) {
//                System.out.print(stack.peek().x + " " + stack.peek().y + " ");
slen += stack.peek().y;
max = Math.max(max, stack.peek().x * slen);
stack.pop();
}
//            System.out.println();

}
return max;
}