Leetcode No.85 Maximal Rectangle
Problem 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.
Input:
[[“1”,”0”,”1”,”0”,”0”],
[“1”,”0”,”1”,”1”,”1”],
[“1”,”1”,”1”,”1”,”1”],
[“1”,”0”,”0”,”1”,”0”]]
Output: 6
Analysis:
This is a typical dynamic programming problem. We keep three matrices: left, right, height, all have the same size as the input. Here’s a great explanation of what these matrices represent from Leetcode user @wahcheung in Chinese. The key to understand this algorithm is clarify what left and right matrix each represents.
In the example above, the left, right, height are as follows:
The maximum rectangle at (i, j) would be calculated as (right(i, j) - left(i, j)) * height(i, j).
In the implementation, in order to reduce space complexity, instead of using actual matrices, we keep three arrays to proceed and update row by row.
Java Code:
1 | public class MaximumRectangle { |