# 最大矩形

给定一个仅包含 01 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

 

示例 1:

输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:
6
解释:
最大矩形如上图所示。

示例 2:

输入:matrix = []
输出:
0

示例 3:

输入:matrix = [["0"]]
输出:
0

示例 4:

输入:matrix = [["1"]]
输出:
1

示例 5:

输入:matrix = [["0","0"]]
输出:
0

 

提示:

以下程序实现了这一功能,请你填补空白处内容: ```java class Solution { public int maximalRectangle(char[][] matrix) { if (matrix == null || matrix.length == 0) return 0; int m = matrix.length; int n = matrix[0].length; int[] left = new int[n]; int[] right = new int[n]; int[] height = new int[n]; Arrays.fill(right, n); int cur_left = 0; int cur_right = n; int res = 0; for (int i = 0; i < m; i++) { cur_left = 0; cur_right = n; for (int j = 0; j < n; j++) { if (matrix[i][j] == '1') height[j]++; else height[j] = 0; } for (int j = 0; j < n; j++) { if (matrix[i][j] == '1') { left[j] = Math.max(left[j], cur_left); } else { left[j] = 0; cur_left = j + 1; } } for (int j = n - 1; j >= 0; j--) { if (matrix[i][j] == '1') { right[j] = Math.min(right[j], cur_right); } else { right[j] = n; cur_right = j; } } ______________________; } return res; } } ``` ## template ```java class Solution { public int maximalRectangle(char[][] matrix) { if (matrix == null || matrix.length == 0) return 0; int m = matrix.length; int n = matrix[0].length; int[] left = new int[n]; int[] right = new int[n]; int[] height = new int[n]; Arrays.fill(right, n); int cur_left = 0; int cur_right = n; int res = 0; for (int i = 0; i < m; i++) { cur_left = 0; cur_right = n; for (int j = 0; j < n; j++) { if (matrix[i][j] == '1') height[j]++; else height[j] = 0; } for (int j = 0; j < n; j++) { if (matrix[i][j] == '1') { left[j] = Math.max(left[j], cur_left); } else { left[j] = 0; cur_left = j + 1; } } for (int j = n - 1; j >= 0; j--) { if (matrix[i][j] == '1') { right[j] = Math.min(right[j], cur_right); } else { right[j] = n; cur_right = j; } } for (int j = 0; j < n; j++) res = Math.max(res, (right[j] - left[j]) * height[j]); } return res; } } ``` ## 答案 ```java for (int j = 0; j < n; j++) res = Math.max(res, (right[j] - left[j]) * height[j]); ``` ## 选项 ### A ```java for (int j = 0; j < n; j++) res = Math.max(res, (right[j] + left[j]) * height[j]); ``` ### B ```java for (int j = 0; j < n; j++) res = Math.max(res, (right[j] + left[j]) / 2 * height[j]); ``` ### C ```java for (int j = 0; j < n; j++) res = Math.max(res, (right[j] - left[j]) / 2 * height[j]); ```