|
1 | 1 | ## Algorithm
|
2 | 2 |
|
| 3 | +[85. Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/) |
| 4 | + |
3 | 5 | ### Description
|
4 | 6 |
|
5 |
| -### Solution |
| 7 | +Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. |
| 8 | + |
| 9 | +Example 1: |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +``` |
| 14 | +Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] |
| 15 | +Output: 6 |
| 16 | +Explanation: The maximal rectangle is shown in the above picture. |
| 17 | +``` |
6 | 18 |
|
7 |
| -```java |
8 | 19 |
|
| 20 | +Example 2: |
| 21 | + |
| 22 | +``` |
| 23 | +Input: matrix = [] |
| 24 | +Output: 0 |
| 25 | +``` |
| 26 | + |
| 27 | +Example 3: |
| 28 | + |
| 29 | +``` |
| 30 | +Input: matrix = [["0"]] |
| 31 | +Output: 0 |
| 32 | +``` |
| 33 | + |
| 34 | +Example 4: |
| 35 | + |
| 36 | +``` |
| 37 | +Input: matrix = [["1"]] |
| 38 | +Output: 1 |
| 39 | +``` |
| 40 | + |
| 41 | +Example 5: |
| 42 | + |
| 43 | +``` |
| 44 | +Input: matrix = [["0","0"]] |
| 45 | +Output: 0 |
| 46 | +``` |
| 47 | + |
| 48 | +Constraints: |
| 49 | + |
| 50 | +- rows == matrix.length |
| 51 | +- cols == matrix[i].length |
| 52 | +- 0 <= row, cols <= 200 |
| 53 | +- matrix[i][j] is '0' or '1'. |
| 54 | + |
| 55 | +### Solution |
| 56 | + |
| 57 | +```java |
| 58 | +class Solution { |
| 59 | + public int maximalRectangle(char[][] matrix) { |
| 60 | + if (matrix == null || matrix.length == 0) { |
| 61 | + return 0; |
| 62 | + } |
| 63 | + int m = matrix.length; |
| 64 | + int n = matrix[0].length; |
| 65 | + int maxA = 0; |
| 66 | + int[] right = new int[n]; |
| 67 | + int[] left = new int[n]; |
| 68 | + int[] heights = new int[n]; |
| 69 | + Arrays.fill(right, n); |
| 70 | + for (int i = 0; i < m; i++) { |
| 71 | + int curleft = 0, curright = n; |
| 72 | + for (int j = 0; j < n; j++) { |
| 73 | + if (matrix[i][j] == '1') { |
| 74 | + heights[j]++; |
| 75 | + } else { |
| 76 | + heights[j] = 0; |
| 77 | + } |
| 78 | + } |
| 79 | + for (int j = 0; j < n; j++) { |
| 80 | + if (matrix[i][j] == '1') { |
| 81 | + // each i has own left[], each will renew |
| 82 | + left[j] = Math.max(curleft, left[j]); |
| 83 | + } else { |
| 84 | + // most next position to zero |
| 85 | + left[j] = 0; |
| 86 | + curleft = j + 1; |
| 87 | + } |
| 88 | + } |
| 89 | + for (int j = n - 1; j >= 0; j--) { |
| 90 | + if (matrix[i][j] == '1') { |
| 91 | + right[j] = Math.min(curright, right[j]); |
| 92 | + } else { |
| 93 | + // remain at last zero position |
| 94 | + right[j] = n; |
| 95 | + curright = j; |
| 96 | + } |
| 97 | + } |
| 98 | + for (int j = 0; j < n; j++) { |
| 99 | + maxA = Math.max(maxA, (right[j] - left[j]) * heights[j]); |
| 100 | + } |
| 101 | + } |
| 102 | + return maxA; |
| 103 | + } |
| 104 | +} |
9 | 105 | ```
|
10 | 106 |
|
11 | 107 | ### Discuss
|
|
0 commit comments