package algorithmbasic.basicsets.class26;
import java.util.Stack;
public class MaximalRectangle {
public static int maximalRectangle(char[][] map) {
int[] height = new int[map[0].length];
int MAX = Integer.MIN_VALUE;
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
height[j] = map[i][j] == '0' ? 0 : height[j] + 1;
}
MAX = Math.max(MAX, maxRecFromBottom(height));
}
return MAX;
}
private static int maxRecFromBottom(int[] height) {
Stack<Integer> stack = new Stack<>();
int MAX = Integer.MIN_VALUE;
for (int i = 0; i < height.length; i++) {
if (stack.isEmpty() || height[i] >= height[stack.peek()]) {
stack.push(i);
continue;
}
while (!stack.isEmpty() && height[i] < height[stack.peek()]) {
int j = stack.pop();
int leftBorder = stack.isEmpty() ? -1 : stack.peek();
int rightBorder = i;
MAX = Math.max(MAX, (rightBorder - leftBorder - 1) * height[j]);
}
stack.push(i);
}
while (!stack.isEmpty()) {
int j = stack.pop();
int leftBorder = stack.isEmpty() ? -1 : stack.peek();
int rightBorder = height.length;
MAX = Math.max(MAX, (rightBorder - leftBorder - 1) * height[j]);
}
return MAX;
}
public static void main(String[] args) {
char[][] map = {{'1', '0', '1', '0', '0'}, {'1', '0', '1', '1', '1'}, {'1', '1', '1', '1', '1'}, {'1', '0', '0', '1', '0'}};
int result = maximalRectangle(map);
System.out.println(result);
}
}