LeetCode - Maximal Rectangle

1 minute read

Problem description

description

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

Example:

1
2
3
4
5
6
7
8
Input:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
Output: 6

Analysis

The first idea is to save continuous 1’s into a 2-d dp array.

So the sample array would be:

1
2
3
4
5
6
[
  [1,0,1,0,0],
  [1,0,3,2,1],
  [5,4,3,2,1],
  [1,0,0,1,0]
]

And then we can check every column, and use the same algorithm in largest-rectangle to solve the maximum area in each column and get a O(MN) solution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class Solution {
    public int maximalRectangle(char[][] matrix) {
        if (matrix == null){
            return 0;
        }
        
        int row = matrix.length;
        if (row == 0){
            return 0;
        }
        
        int col = matrix[0].length;
        if (col == 0){
            return 0;
        }
        
        int[][] dp = new int[row+1][col+1]; 
        
        for (int i = 1; i<row+1; i++){
            for (int j = 1; j< col+1; j++){
                if (matrix[i-1][j-1] == '1' && dp[i][j - 1] != 0){
                    dp[i][j] = dp[i][j-1] - 1;
                }
                else if (matrix[i-1][j-1] == '1') {
                    int count = 0;
                    while (j+count-1 < col && matrix[i-1][j+count-1] == '1'){
                        count++;
                    }
                    dp[i][j] = count;
                }
            }
        } 
        
        int max = 0;
        
        for (int j = 1; j < col+1; j++){
            int[] lessFromLeft = new int[row+1];
            int[] lessFromRight = new int[row+1];
            
            lessFromRight[row] = row+1;
            lessFromLeft[1] = 0;
            
            for (int i = 2; i < row+1; i++){
                int p = i - 1;
                
                while (p >= 1 && dp[p][j] >= dp[i][j])
                    p = lessFromLeft[p];
                
                lessFromLeft[i] = p;
            }
            
            for (int i = row; i >= 1; i--){
                int p = i + 1;
                
                while (p < row + 1 && dp[p][j] >= dp[i][j])
                    p = lessFromRight[p];
                
                lessFromRight[i] = p;
            }
            
            for (int i = 1; i < row+1; i++){
                max = Math.max(max, (lessFromRight[i] - lessFromLeft[i] - 1) * dp[i][j]);
            }
            
        }
        
        return max;
    }
}

What to improve

  • be sensitive about learned problem.