LeetCode – Maximal Rectangle (Java)

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

Analysis

This problem can be converted to the "Largest Rectangle in Histogram" problem.

Java Solution

public int maximalRectangle(char[][] matrix) {
	int m = matrix.length;
	int n = m == 0 ? 0 : matrix[0].length;
	int[][] height = new int[m][n + 1];
 
	int maxArea = 0;
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			if (matrix[i][j] == '0') {
				height[i][j] = 0;
			} else {
				height[i][j] = i == 0 ? 1 : height[i - 1][j] + 1;
			}
		}
	}
 
	for (int i = 0; i < m; i++) {
		int area = maxAreaInHist(height[i]);
		if (area > maxArea) {
			maxArea = area;
		}
	}
 
	return maxArea;
}
 
private int maxAreaInHist(int[] height) {
	Stack<Integer> stack = new Stack<Integer>();
 
	int i = 0;
	int max = 0;
 
	while (i < height.length) {
		if (stack.isEmpty() || height[stack.peek()] <= height[i]) {
			stack.push(i++);
		} else {
			int t = stack.pop();
			max = Math.max(max, height[t]
					* (stack.isEmpty() ? i : i - stack.peek() - 1));
		}
	}
 
	return max;
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Yinglei Zhang

    This is pretty awesome. Finding connections between different problems is better than solving the problem itself.

  • Simon

    I have a more elegant implement about it.

  • Kyle

    It’s very cool that you converted a problem to another. Brilliant!!

  • Kyle

    It will not. Because height[] has one additional element at the end which is 0 ( int[][] height = new int[m][n + 1];) . So even if the elements are in increasing order, zero will be at the end, so non increasing. 🙂

  • Guangyu Wang

    Hi, I have a question about the maxAreaInHist() method: if the heights are in ascending order, the max will remain zero all the time. This is a bug right?