Tutorialspoint
Problem
Solution
Submissions

Maximal Rectangle

Certification: Advanced Level Accuracy: 100% Submissions: 1 Points: 15

Write a Java program to find the largest rectangle containing only 1's in a binary matrix. The rectangle can be formed by any set of adjacent cells containing '1's. Return the area of the largest such rectangle.

Example 1
  • Input: matrix = [
     ["1","0","1","0","0"],
     ["1","0","1","1","1"],
     ["1","1","1","1","1"],
     ["1","0","0","1","0"] ]
  • Output: 6
  • Explanation: In the third row, from column 1 to 4, we have consecutive 1's forming a rectangle of height 1 and width 4 with area 4. However, if we consider columns 2-4, we can extend this to the second row, forming a 2x3 rectangle with area 6.
Example 2
  • Input: matrix = [
     ["0","1","1","0"],
     ["1","1","1","1"],
     ["1","1","1","1"],
     ["0","1","0","0"] ]
  • Output: 8
  • Explanation: In rows 1 and 2, columns 0-3, we have a 2x4 rectangle of 1's with area 8. There are other rectangles of 1's, but none with area greater than 8.
Constraints
  • rows == matrix.length, cols == matrix[i].length
  • 0 ≤ rows, cols ≤ 200
  • matrix[i][j] is '0' or '1'
  • Time Complexity: O(rows * cols)
  • Space Complexity: O(cols)
MatrixAccentureAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a histogram-based approach to solve this problem
  • For each row, calculate the heights of the "bars" in the histogram
  • Then, for each row, find the largest rectangle in the histogram
  • Use a stack-based approach to find the largest rectangle in each histogram
  • Keep track of the maximum area found so far
  • When a cell is '0', reset the height of that column to 0

Steps to solve by this approach:

 Step 1: Convert the 2D problem into a series of 1D problems using histograms.

 Step 2: For each row, calculate the height of the histogram at each position by counting consecutive '1's above (including the current row).
 Step 3: Implement a function to find the largest rectangle in each histogram.
 Step 4: For each histogram, use a stack-based approach to find the largest rectangle area.
 Step 5: Use two arrays to record the left and right boundaries for each bar in the histogram.
 Step 6: Calculate the area for each bar using its height and width (right boundary - left boundary - 1).
 Step 7: Return the maximum area found across all row histograms.

Submitted Code :