Given a matrix (H × W) which contains only 1 and 0, find the area of the largest rectangle which only contains 0s.
Constraints
1 ≤ H, W ≤ 1,400
Input
H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W
In the first line, two integers H and W separated by a space character are given. In the following H lines, ci,j, elements of the H × W matrix, are given.
Output
Print the area (the number of 0s) of the largest rectangle.
Example
Input
4 5
0 0 1 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 1 0
Output
6
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to find the largest all-zero rectangle in a binary matrix (1 and 0). Constraints H,W up to 1400, so O(HW) or O(HWlog?) but typical solution: maximal rectangle in binary matrix problem can be solved in O(HW) using histogram method. Since we only care about zeros, we can treat zeros as '1's and ones as '0's. Then the problem reduces to maximal rectangle of ones. Classic solution: for each row, compute heights of bars (consecutive zeros up to this row) and then for each row find the largest rectangle in histogram. That gives O(H*W) if we process each row with a stack.
But note constraints up to 1400^2 = 1,960,000 cells, which is fine. So we can do O(H*W). The typical algorithm:
Initialize an array height of length W, all zeros.
For each row i from 0 to H-1:
For each column j, if matrix[i][j] == 0, then height[j] += 1, else height[j] = 0.
Then compute the largest rectangle area in histogram given height. Using a stack method that processes each bar once, overall O(W) per row. So total O(H*W).
Edge cases: empty? H,W>=1.
We need to parse input: first line H W, then H lines of numbers (space separated). They are given as integers. So we can read them.
We need to output area.
But there is nuance: the example: 4x5 matrix, answer is 6. Let's check: The largest rectangle of zeros. Possibly 2x3 rectangle? Let's see positions: Coordinates (row, col) from 0? Possibly rows:
Row0: 0 0 1 0 0
Row1: 1 0 0 0 0
Row2: 0 0 0 1 0
Row3: 0 0 0 1 0
Alternatively, rows 0-1 cols 1-4? But row0 col2=1 breaks; row1 col1-4 zeros? Row1: 1 0 0 0 0 so cols1-4 are 0,0,0,0 (4 zeros) but row0 col1=0, col2=1 so can't include col2. Maybe rectangle rows 0-2 cols 3-4? Row0 col3=0 col4=0; row1 col3=0 col4=0; row2 col3=1 breaks. So not.
So algorithm works.
Implementation details: use Python? The environment? Likely accept Python code. But careful with recursion depth? Not needed.
We'll implement:
def max_rectangle_area(heights):
stack = []
max_area = 0
for i, h in enumerate(heights):
start = i
while stack and stack[-1][1] > h:
index, height = stack.pop()
max_area = max(max_area, height * (i - index))
start = index
stack.append((start, h))
# After processing all bars
for i, h in stack:
max_area = max(max_area, h * (len(heights) - i))
return max_area
But careful: In the typical histogram algorithm, we push (index, height) and when we get a bar lower than top, we pop top and compute area with height and width = current index - popped index. Then the new bar's start index becomes popped index. Works.
Alternatively we can use sentinel heights with 0 at end.
Now main:
Read H, W = map(int, input().split())
heights = [0] * W
ans = 0
for i in range(H):
row = list(map(int, input().split()))
for j in range(W):
if row[j] == 0:
heights[j] += 1
else:
heights[j] = 0
ans = max(ans, max_rectangle_area(heights))
print(ans)
Edge Cases: Large values, but area up to H*W <= 1,960,000, fits in int.
We need to ensure the algorithm is efficient: O(H*W) with Python lists. Should be fine.
But there is also a dynamic programming approach but stack is fine.
Potential Pitfall: Input format: numbers separated by spaces. Could have extra spaces? But typical.
Also, note that the problem is known as "Largest rectangle in a binary matrix" but with zeros as ones.
Alternative: Since we only have 0s and 1s, we could treat zeros as 1 and ones as 0. So algorithm remains same.
Let's double-check the histogram function with sample:
Initialize heights = [0,0,0,0,0]
Row0: 0 0 1 0 0 -> heights become [1,1,0,1,1] (since at col2, 1 -> height=0). Compute max rectangle: For [1,1,0,1,1], max area? Let's compute: At row0 alone, largest rectangle of height1 width5? But col2 height 0, so rectangle can't cross that. So possible: width2 area2 (cols0-1), width2 area2 (cols3-4). Actually maybe area 2. So max so far 2.
Row1: row1 = 1 0 0 0 0 -> update: col0: 1? Actually row1[0]=1 -> height[0]=0; col1:0 -> height[1]=2; col2:0 -> height[2]=1 (since previous 0, now 0 so +1? Actually col2 previous height 0, plus 1 if current 0? row1[2]=0, so height[2] becomes 1); col3:0 -> height[3]=2; col4:0 -> height[4]=2. So heights = [0,2,1,2,2]. Compute max rectangle: Histogram [0,2,1,2,2] -> largest rectangle area? Consider heights: At col1 height2, can extend left to index? left bound is index1 because col0=0 lower, right bound? col2 height1 lower, so width1 area2; col2 height1 can extend left to index? left bound index? col1 height2 >=1, but after popping, maybe? Actually compute: i=0 h=0 -> stack: (0,0) (start index 0). i=1 h=2 -> while stack top (0,0) not >2 so push (1,2). i=2 h=1 -> top (1,2) >1 -> pop (1,2) area = 2*(2-1)=2, start=1. stack now (0,0). push (1,1). i=3 h=2 -> top (1,1) <=2, push (3,2)?? Actually we push (start, h) after while loop; start computed as popped index. For i=3, stack contains (0,0),(1,1). while top (1,1) >2? No, 1>2 false. So push (3,2). i=4 h=2 -> stack: (0,0),(1,1),(3,2). while top (3,2) >2? false. push (4,2). After loop, process remaining: (0,0) area=0, (1,1) area=1*(5-1)=4? Actually index=1, height=1, width=5-1=4 area4; (3,2) area=2*(5-3)=4; (4,2) area=2*(5-4)=2. So max area=4. So ans=4.
Row2: row2 = 0 0 0 1 0 -> update: col0:0 -> heights[0] becomes 1; col1:0 -> heights[1]=3; col2:0 -> heights[2]=2; col3:1 -> heights[3]=0; col4:0 -> heights[4]=3? Actually previous height[4]=2, plus 0? row2[4]=0 -> heights[4]=3. So heights = [1,3,2,0,3]. Compute max rectangle: Histogram [1,3,2,0,3]. Largest area? Possibly at col1 height3, extend left? col0=1, so left bound index0? Actually col0 height1<3, so left bound index1; right bound limited by col2 height2<3, so width1 area3. Or rectangle formed by col1,col2? With heights 3 and 2, the max rectangle of min height 2 width2 area4. But also maybe at col4 height3, left bound? col3=0 lower, so width1 area3. Also col2 height2 can extend to col1? But col1 height3>=2, so width2 area4. And col0 height1 width5? but col3=0 breaks. So max area=4? Actually we can compute: After processing, should get area maybe 4. But the known largest rectangle after row2 should be 6? Actually not yet: after row2, we have rows 0-2; largest all-zero rectangle up to row2 might be rows 1-2 cols 1-3? But col3 row2 is 1 so no. rows 2 only? But row2 zeros at cols0-2 and col4, but col3 is 1. So largest could be 2x2? rows 1-2 cols 1-2? That area 4. So max area stays 4.
Row3: row3 = 0 0 0 1 0 -> update: col0:0 -> heights[0]=2; col1:0 -> heights[1]=4; col2:0 -> heights[2]=3; col3:1 -> heights[3]=0; col4:0 -> heights[4]=4. So heights = [2,4,3,0,4]. Compute max rectangle: Likely area 6 from columns 0-2 with height? The rectangle of zeros rows2-3 cols0-2: heights? At col0 height2, col1 height4, col2 height3. The largest rectangle in histogram might be from col1 and col2: min height3 width2 area6? Actually col1=4, col2=3, so rectangle spanning both columns with height3 gives area 6. Also col1 alone height4 area4. col0 height2 width3? but col3=0 limits width? Actually from col0 to col2, min height is 2? Because col0=2, col1=4, col2=3 => min=2, width=3 area6. So max area=6. Yes.
Thus final answer 6.
So algorithm works.
We'll produce Python code.
Potential optimizations: Using list of ints, stack as list of tuples, but could also use two arrays for indices and heights. But fine.
Memory: O(W) for heights and stack.
Now about reading input: Use sys.stdin.read() for speed? HW up to ~2e6, reading line by line with input() might be okay but may be slow. But typically judge accepts Python with input() for 2e6 numbers? Using sys.stdin.buffer.read() and splitting into ints could be faster. However, H and W <= 1400, so HW <= 1,960,000, reading each line with input().split() 1400 lines is okay. But each line could have up to 1400 numbers, so using sys.stdin.read() might be safer.
But we can implement with sys.stdin.buffer.read() to parse all ints quickly. I'll write:
import sys
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
H = int(next(it))
W = int(next(it))
heights = [0] * W
ans = 0
for i in range(H):
for j in range(W):
val = int(next(it))
if val == 0:
heights[j] += 1
else:
heights[j] = 0
# compute max rectangle in current histogram
stack = []
for idx, h in enumerate(heights):
start = idx
while stack and stack[-1][1] > h:
pi, ph = stack.pop()
area = ph * (idx - pi)
if area > ans:
ans = area
start = pi
stack.append((start, h))
# after row
for pi, ph in stack:
area = ph * (W - pi)
if area > ans:
ans = area
print(ans)
if name == "main":
main()
But we need to be careful: The stack approach within the row loop recomputes the max area for that histogram. But we should avoid recomputing for each row? Actually we need to compute per row. That's fine.
But note: We're using heights array and updating per row, and then computing max area. That's typical.
Alternatively, we could compute after each row, but the stack processing loops over W each time. So total O(H*W).
We must ensure that we reset heights properly for rows where value is 1.
Testing with sample:
Let's simulate quickly with code mental: It should output 6.
Edge Cases:
All ones: heights all 0 each row, max area remains 0 -> answer 0.
All zeros: heights become increments each row, eventually heights = [H]W, and the histogram max area = HW -> answer H*W.
We should test with a simple case: H=1, W=1, matrix=0 -> heights=[1] -> stack: push (0,1), then after row, compute area 1*(1-0)=1 -> ans=1. Good.
If matrix=1 -> heights=[0] -> ans remains 0.
But careful: When heights has 0 bars, the stack algorithm may push (start, 0) and later compute areas for zero? Actually for h=0, while stack and top >0? Usually while stack and top[1] > h, then if h=0, it will pop all bars because they are >0, computing area for each popped bar. Then after popping, start becomes the smallest index among popped bars, and then we push (start, 0). This is correct. But then after the row, we process remaining stack entries, which include the zero bar. However area for zero is zero. So fine.
But we should consider memory: stack may hold up to W entries.
Now, we need to be careful about integer overflow? Not an issue.
Time complexity: H up to 1400, W up to 1400, so 1.96 million cells. For each row, we update W values (O(W)) and run stack algorithm O(W). So total about 2 * H * W = ~4 million operations, which is fine.
But Python overhead for loop inside loop: each row we have inner j loop for update and then a loop for stack. That's fine.
Alternatively, we can combine the histogram computation with the update in one pass? But separate is okay.
One possible micro-optimization: Instead of recomputing max rectangle from scratch each row, we could use DP but not needed.
Make sure to use local variables for speed within loops: e.g., assign heights_j = heights[j] but not necessary.
We can also implement the histogram function as a separate function for clarity but that adds function call overhead for each row. Might be okay, but to be safe we can inline.
But I think it's fine.
Now produce final answer.
But wait: The problem statement says "largest rectangle which only contains 0s." In a binary matrix, rectangle is contiguous submatrix. So our algorithm is correct.
One nuance: The rectangle must be composed entirely of zeros. The histogram method works for maximal all-1's rectangle; we treat zeros as 1. So correct.
Thus solution is as above.
Now produce final answer: code in Python.
But we need to output the area.
We'll ensure we use sys.stdin.buffer for fast reading.
Also, we can reduce overhead: Instead of converting each token to int for each element twice? Not needed.
We'll read all ints, iterate.
Implementation details: In the update loop, we have to process each row's W ints. We'll use:
for i in range(H):
for j in range(W):
if next(it) == b'0': # because split returns bytes
heights[j] += 1
else:
heights[j] = 0
But next(it) returns bytes, we can compare to b'0' or convert to int. Since we need to know if it's 0 or 1, we can check if val == 48? But easier to convert to int via int(val). But conversion for each token may be overhead. But we have only 2e6 tokens, conversion is fine. But we can do: val = next(it); if val == b'0': heights[j] += 1 else: heights[j] = 0. Since we know it's either 0 or 1. So we can avoid int conversion. However, we need to ensure we treat b'0' correctly. But using int conversion is simpler and still acceptable.
But reading all tokens as bytes and comparing to b'0' is faster. However, the input format uses spaces and newlines, but numbers are ascii digits. So tokens are b'0' or b'1'. So we can do:
c = next(it)
if c == b'0':
heights[j] += 1
else:
heights[j] = 0
This avoids conversion. But careful: If there might be extra spaces? It's fine. And H and W are ints; we can convert them first using int.
So code:
import sys
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
H = int(next(it))
W = int(next(it))
heights = [0] * W
ans = 0
for i in range(H):
for j in range(W):
# value is b'0' or b'1'
if next(it) == b'0':
heights[j] += 1
else:
heights[j] = 0
# compute max rectangle area in histogram heights
stack = []
for idx, h in enumerate(heights):
start = idx
while stack and stack[-1][1] > h:
pi, ph = stack.pop()
area = ph * (idx - pi)
if area > ans:
ans = area
start = pi
stack.append((start, h))
for pi, ph in stack:
area = ph * (W - pi)
if area > ans:
ans = area
print(ans)
Processing: H=4, W=5. Then for each row we read W tokens.
We need to ensure that the order of tokens matches rows. Yes.
Now, inside the update loop, we read a token and compare to b'0'. For row0, tokens: b'0', b'0', b'1', b'0', b'0' -> heights become [1,1,0,1,1] after row0.
Then compute histogram: works.
Then row1: tokens b'1', b'0', b'0', b'0', b'0' -> heights become [0,2,1,2,2].
... etc.
At the end ans=6.
Thus correct.
But one subtlety: In the histogram algorithm, when we process a bar of height h, we pop while stack top's height > h. For bars with equal height, we don't pop because condition is >, not >=. That's correct: If we have equal heights, the rectangle can extend to the right as well; by not popping, the start index remains earlier for later bars? Actually typical algorithm uses >= to set left boundary. But there are variations. Using > ensures that when heights are equal, the rectangle will be extended by the later bar with same height, but we must ensure the area computed correctly. Let's think: In histogram, if we have consecutive bars of equal height, the largest rectangle spanning them will be considered when we encounter the last bar or when we process after the loop. Using only > to pop, we will keep the earliest index for that height. When encountering a bar of equal height, we don't pop, so the start index remains the current idx? Actually we compute start = idx, but then while stack and top > h: no pop, so start = idx unchanged, then we push (start, h) = (idx, h). This means we are pushing a new entry with start idx = current idx, not the earlier index. However, for equal heights, the rectangle should be able to extend leftwards. Consider heights [2,2]. When processing i=0: push (0,2). i=1: h=2, while top? top (0,2) > 2? false, so push (1,2). Then after loop, we process stack: (0,2) area = 2*(2-0)=4, (1,2) area = 2*(2-1)=2. So the area 4 is computed correctly. So it's fine. The alternative with >= would pop the previous bar and push with earlier index, leading to only one bar with width 2, also works. Both work, but need to ensure that when we compute area for the popped bar, we use its original start index which is correct. With > we compute area for bar at index 0 when it is popped? It's not popped because 2>2 false. So area computed at the end. So both fine.
But be careful: When we have decreasing heights, we pop and compute area. That's correct.
Now, what about the sentinel? At the end we process remaining bars with width = W - start index. Works.
Now, we also compute ans after each row. Good.
Potential bug: When we compute area in the while loop, we use area = ph * (idx - pi). But note that pi is the start index of that bar. When we popped it, its rectangle can extend from pi to idx-1 inclusive, width = idx - pi. That's correct because heights in between are >= ph (since we popped only when encountering a lower bar). So width is correct.
Then after processing all bars, for each remaining bar (pi, ph), the rectangle can extend to the end, width = W - pi.
Thus correct.
Now, we also need to consider large recursion? No recursion.
Now, time: H=1400, W=1400, loops: for each row, we have a for j in range(W): O(W). Then another for idx, h in enumerate(heights): O(W). So total ~2HW=~4e6 iterations. Inside second loop, while loop may pop, but each element popped once per row. So O(W). So overall about 4 million operations plus overhead of Python loops, but that's fine.
But note: H and W up to 1400, H*W = 1.96 million, times 2 = about 4 million. Python can handle within time limit.
But careful: The input reading using .split() will create a list of about 2 million bytes tokens, which is okay memory-wise: each token is a bytes object representing a small string, overhead maybe 33-50 bytes each, 2 million * 50 = 100 MB, which might be high. Actually 1.96 million numbers plus 2 = about 2 million tokens. Each bytes object overhead is significant: Python's bytes object for small numbers may be around 33 bytes (depending on implementation). 2e6 * 33 = 66 MB, plus list overhead (8 bytes per pointer) 16 MB, total ~82 MB. Could be borderline but likely acceptable? However, typical memory limit might be 256 MB or 512 MB, so 80 MB is okay. But there is also the matrix not stored, only heights array. So memory usage is dominated by the token list. Could we avoid storing all tokens? Better to read line by line. Using sys.stdin.buffer.readline in a loop is more memory efficient. Since H is only 1400, reading line by line is fine and avoids large memory overhead.
Thus, we can adopt line by line reading to reduce memory. Let's do:
import sys
def main():
import sys
H_W = sys.stdin.buffer.readline().split()
H = int(H_W[0])
W = int(H_W[1])
heights = [0]*W
ans = 0
for i in range(H):
row = sys.stdin.buffer.readline().split()
# row length should be W
for j in range(W):
# row[j] is bytes, e.g., b'0' or b'1'
if row[j] == b'0':
heights[j] += 1
else:
heights[j] = 0
# histogram
stack = []
for idx, h in enumerate(heights):
start = idx
while stack and stack[-1][1] > h:
pi, ph = stack.pop()
area = ph * (idx - pi)
if area > ans:
ans = area
start = pi
stack.append((start, h))
for pi, ph in stack:
area = ph * (W - pi)
if area > ans:
ans = area
print(ans)
That reads each line, splits it into a list of bytes of length W. That uses O(W) per row temporary, which is fine. This way, we don't store all tokens, memory is low.
Potential issue: Input lines might have extra spaces? Using split() handles that.
Edge: After reading H and W, the next lines may have trailing spaces, but split removes.
Now, maybe we can micro-opt histogram by using list of ints for stack indices and heights separate. But not needed.
Now, we must produce final answer.
But let's think about alternative cases: If the largest rectangle is in later rows, ans accumulates.
We also need to consider if the rectangle could be of size 0? If no zeros, ans=0.
Now, final code.
However, one more thing: The algorithm as described works for "largest rectangle containing only 1's" when we treat zeros as 1's. But in our update, if matrix[i][j] == 0, we increment heights[j]; else we set to 0. That builds a histogram of consecutive zeros upward. So each bar's height is the number of consecutive zeros ending at that row. Then the maximum rectangle in the histogram corresponds to a rectangle of zeros with bottom at the current row. So we capture all possibilities. Good.
Now, could there be a rectangle that is not anchored at the bottom row? The algorithm considers each row as the base row, so eventually the rectangle's bottom row will be considered. So it's exhaustive.
Thus solution is correct.
Now, we should produce final answer with explanation.
Since the user asked for code? Actually the user said "Given a matrix ... find the area ...". This is a problem statement; we need to produce a solution. The typical output is just the code? Usually on such platforms, we provide code. Since this is a reasoning environment, we should output final code.
But the instruction: We need to respond with final answer: the code in Python.
Thus, final.
But we can include comments.
Now produce final code.
Also, we can use list comprehension but fine.
Potential performance: The inner while loop could cause many operations, but each element popped once.
We can also implement the histogram function as a function with sentinel to avoid second loop, but fine.
Now, final answer.
But note: The problem might have constraints that require O(H*W) and memory, but this meets.
Let's write final answer.
We'll output:
python
import sys
def main():
H, W = map(int, sys.stdin.buffer.readline().split())
heights = [0] * W
ans = 0
for _ in range(H):
row = sys.stdin.buffer.readline().split()
# update heights
for j in range(W):
if row[j] == b'0':
heights[j] += 1
else:
heights[j] = 0
# largest rectangle in histogram
stack = [] # each element: (index, height)
for i, h in enumerate(heights):
start = i
while stack and stack[-1][1] > h:
idx, height = stack.pop()
area = height * (i - idx)
if area > ans:
ans = area
start = idx
stack.append((start, h))
for idx, height in stack:
area = height * (W - idx)
if area > ans:
ans = area
print(ans)
if __name__ == "__main__":
main()
But careful: In while loop, we compute area for popped bar. That's correct. After processing all bars, we handle remaining.
Check: When heights are like [2,1], processing: i=0, h=2 -> stack empty, push (0,2). i=1, h=1 -> while stack top (0,2) >1: pop, area = 2*(1-0)=2, start=0. Then push (0,1). After loop, stack has (0,1). Then remaining: area = 1*(2-0)=2. So ans=2. Good.
Edge: heights like [1,2,3]: i=0 push(0,1); i=1 h=2 -> no pop, push(1,2); i=2 h=3 -> push(2,3); after loop, process stack: (0,1) area=13=3, (1,2) area=22=4, (2,3) area=3*1=3 -> ans=4. Actually correct rectangle is width 2 height 2? Actually histogram [1,2,3] largest rectangle is? Could be at index1 height2 width2 area4, or index2 height3 width1 area3. So ans=4. Good.
Thus correct.
Now, note: We used row[j] == b'0' comparison; but what if the input includes numbers with leading zeros? Not, only 0 or 1.
Alternatively, we can convert to int: if int(row[j]) == 0: but that's slower. Using direct byte compare is fine.
But to be safe, we could use row[j] == b'0' because tokens are exactly '0' or '1'.
Now, finalize.
We might also consider using an array of ints for heights and stack as two lists: positions and heights. But fine.
Now, let's provide the answer. ```python
import sys
def main():
H, W = map(int, sys.stdin.buffer.readline().split())
heights = [0] * W # histogram of consecutive zeros above current row
ans = 0
code
for _ in range(H):
row = sys.stdin.buffer.readline().split()
# update the histogram
for j in range(W):
if row[j] == b'0':
heights[j] += 1
else:
heights[j] = 0
# largest rectangle in histogram (stack based)
stack = [] # each element: (index, height)
for i, h in enumerate(heights):
start = i
while stack and stack[-1][1] > h:
idx, height = stack.pop()
area = height * (i - idx)
if area > ans:
ans = area
start = idx
stack.append((start, h))
# process bars that extend to the end
for idx, height in stack:
area = height * (W - idx)
if area > ans:
ans = area
print(ans)