Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Stack & Queue

Maximal Rectangle of 1s

Hard · Stack & Queue · Asked at Google, Amazon, Meta, Microsoft

In a grid of 0s and 1s, find the largest rectangle (aligned with the grid) that contains only 1s and print its area.

Input

First line: r c. Next r lines: c values (0 or 1).

Output

The largest area.

Constraints

Treat each row as the floor of a histogram: height[j] = number of consecutive 1s ending at this row in column j. The best rectangle with its bottom on this row is the largest rectangle in that histogram — solved in O(c) with a monotonic stack.

Example 1

Input

4 5
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output

6

Example 2

Input

1 1
0

Output

0

Hints

  1. Fix the bottom row of the rectangle.
  2. For each column, how many consecutive 1s end at this row? That is a histogram.
  3. The best rectangle with this bottom row is the largest rectangle in that histogram.

Approach

Maintain heights[j] across rows: heights[j] + 1 if the cell is 1, else 0. After each row, compute the largest rectangle in the histogram with a monotonic stack of increasing heights: when a lower bar arrives, pop taller bars and measure each popped bar's rectangle, whose width runs from just after the new stack top to the current index. A sentinel bar of height 0 at the end empties the stack.

Complexity: O(r · c) time · O(c) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int R, C;
    cin >> R >> C;
    vector<int> h(C, 0);
    long long best = 0;
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++) {
            int x;
            cin >> x;
            h[j] = x ? h[j] + 1 : 0;
        }
        vector<int> st;
        for (int j = 0; j <= C; j++) {
            int cur = j == C ? 0 : h[j];
            while (!st.empty() && h[st.back()] >= cur) {
                long long height = h[st.back()];
                st.pop_back();
                int left = st.empty() ? 0 : st.back() + 1;
                best = max(best, height * (j - left));
            }
            st.push_back(j);
        }
    }
    cout << best << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
R, C = data[0], data[1]
h = [0] * C
best = 0
p = 2
for i in range(R):
    for j in range(C):
        h[j] = h[j] + 1 if data[p + j] else 0
    p += C
    st = []
    for j in range(C + 1):
        cur = h[j] if j < C else 0
        while st and h[st[-1]] >= cur:
            height = h[st.pop()]
            left = st[-1] + 1 if st else 0
            if height * (j - left) > best:
                best = height * (j - left)
        st.append(j)
print(best)

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int R = (int) in.nval;
        in.nextToken();
        int C = (int) in.nval;
        int[] h = new int[C];
        int[] st = new int[C + 1];
        long best = 0;
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                in.nextToken();
                h[j] = in.nval == 1 ? h[j] + 1 : 0;
            }
            int top = 0;
            for (int j = 0; j <= C; j++) {
                int cur = j == C ? 0 : h[j];
                while (top > 0 && h[st[top - 1]] >= cur) {
                    long height = h[st[--top]];
                    int left = top == 0 ? 0 : st[top - 1] + 1;
                    best = Math.max(best, height * (j - left));
                }
                st[top++] = j;
            }
        }
        System.out.println(best);
    }
}

Solve Maximal Rectangle of 1s online · All practice problems