VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-size-rectangle-binary-sub-matrix-1s/

⇱ Maximum Area Rectangle of 1s in a Binary Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Area Rectangle of 1s in a Binary Matrix

Last Updated : 15 Sep, 2025

Given a 2D binary matrix mat[][] consisting only of 0s and 1s, find the area of the largest rectangle sub-matrix that contains only 1s.

Examples:

Input: mat[][] = [[0, 1, 1, 0],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 0, 0]]
Output: 8
Explanation: The largest rectangle with only 1's is from (1, 0) to (2, 3) which is

👁 409843080


Input: mat[][] = [[0, 1, 1],
[1, 1, 1],
[0, 1, 1]]
Output: 6
Explanation: The largest rectangle with only 1's is from (0, 1) to (2, 2) which is

👁 409843081

[Approach 1] Using Largest Rectangular Area in a Histogram - O(n*m) Time and O(m) Space

Instead of directly searching the whole matrix, think row by row. For every row, treat it as the base of a rectangle and see how far rectangles of 1’s can extend upward.

Build Heights Array

  • Maintain an array height[] where height[j] stores the count of consecutive 1’s in column j up to the current row.
  • If you encounter a 0, reset that column’s height to 0.

Now, after updating height[] for a row, the problem becomes identical to finding the largest rectangle area in a histogram formed by height[].

The idea is to treat each row as the ground and encode vertical runs of 1’s into a histogram (height[]). Then the known stack-based largest-rectangle-in-histogram gives the max area for that base repeat for all rows and take the max.


Output
8

[Approach 2] Using Dynamic Programming - O((n^2)*m) Time and O(n*m) Space

The idea is to store, for each cell (i, j), the width of consecutive 1’s ending at that position in a 2D array. Then, for every cell (i, j) with value 1, iterate upwards row by row. While moving upward, keep track of the minimum width of 1’s seen so far in that column. This ensures the rectangle formed remains valid. At each step, the rectangle area is computed as: (area = minWidth * height)


Output
8

Related articles:

Comment