Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
思路:
如上图所示,我们以i行为底边,比如以第5行为底边,则每一列的高度为[2, 5, 4, 0];
问题可以转变为求面积最大的柱形区间,因而问题可以转化成;
我们需要计算以每一行为底边时的最大面积,当计算得到以最后一行为底边的最大面积时,即为问题的解。
代码如下:
public int maximalRectangle(char[][] matrix) { if(matrix == null || matrix.length == 0) return 0; int m = matrix.length; int n = matrix[0].length; int[] A = new int[n]; int max = 0; for(int i=0; istack = new Stack (); int current = 0; int max = 0; for(int i=0; i<=A.length;) { if(i == A.length) { current = 0; } else { current = A[i]; } if(stack.isEmpty() || current > A[stack.peek()]) { stack.push(i); i++; } else { int height = A[stack.pop()]; int length = stack.isEmpty() ? i : i - stack.peek() - 1; max = Math.max(max, height * length); } } return max; }