Maximal Rectangle

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:

Input:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
Output: 6
public class Solution {
    public int maximalRectangle(char[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return 0;
        int cLen = matrix[0].length; // Number of columns
        int rLen = matrix.length; // Number of rows
        // Histogram array
        int[] hist = new int[cLen];
        int max = 0;
        for (int row = 0; row < rLen; row++) {
            // Create histogram
            for (int i = 0; i < cLen; i++)
                hist[i] = matrix[row][i] == 0 ? 0 : hist[i] + 1;
            // Find max rectangle in histogram
            Stack<Integer> st = new Stack<>();
            int[] left = new int[cLen];
            int[] right = new int[cLen];
            // Find closest smaller element on left
            for (int i = 0; i < cLen; i++) {
                while (st.size() != 0 && hist[st.peek()] >= hist[i])
                    st.pop();
                if (st.size() == 0)
                    left[i] = -1;
                else
                    left[i] = st.peek();
                st.push(i);
            }
            st.clear();
            // Find closest smaller element on right
            for (int i = cLen - 1; i >= 0; i--) {
                while (st.size() != 0 && hist[st.peek()] >= hist[i])
                    st.pop();
                if (st.size() == 0)
                    right[i] = n;
                else
                    right[i] = st.peek();
                st.push(i);
            }
            for (int x : hist)
                max = Math.max(max, hist[i] * (right[i] - left[i] - 1));
        }
        return max;
    }
}

Last updated