Skip to content

Commit 11e7d65

Browse files
authored
Merge pull request #1114 from katarianikita2003/main
Create 0085-Maximal-Rectangle
2 parents 0031507 + 1a9096b commit 11e7d65

File tree

1 file changed

+269
-0
lines changed

1 file changed

+269
-0
lines changed
Lines changed: 269 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,269 @@
1+
---
2+
id: Maximal-Rectangle
3+
title: Maximal Rectangle
4+
sidebar_label: Maximal Rectangle
5+
tags:
6+
- algorithms
7+
- dynamic programming
8+
- stack
9+
- matrix
10+
- binary matrix
11+
- rectangle
12+
---
13+
14+
## Problem Description
15+
16+
| Problem Statement | Solution Link | LeetCode Profile |
17+
| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ |
18+
| [Maximal-Rectangle](https://leetcode.com/problems/Maximal-Rectangle/description/) | [Maximal-Rectangle Solution on LeetCode](https://leetcode.com/problems/Maximal-Rectangle/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) |
19+
20+
### Problem Description
21+
22+
Given a `rows x cols` binary matrix filled with `0's` and `1's`, find the largest rectangle containing only `1's` and return its area.
23+
24+
### Examples
25+
26+
#### Example 1:
27+
**Input:** `matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]`
28+
**Output:** `6`
29+
**Explanation:** `The maximal rectangle is shown in the above picture.`
30+
31+
#### Example 2:
32+
**Input:** `matrix = [["0"]]`
33+
**Output:** `0`
34+
35+
36+
#### Example 3:
37+
**Input:** `matrix = [["1"]]`
38+
**Output:** `1`
39+
40+
41+
### Constraints
42+
43+
- `rows == matrix.length`
44+
- `cols == matrix[i].length`
45+
- `1 <= rows, cols <= 200`
46+
- `matrix[i][j]` is `'0'` or `'1'`.
47+
48+
## Approach
49+
50+
1. **Transform the Matrix into Histograms**: For each row in the matrix, treat each column as the height of a histogram bar.
51+
2. **Use Histogram Technique**: Apply the largest rectangle in histogram technique for each row.
52+
3. **Dynamic Update**: Update the heights of the histogram bars dynamically while iterating over rows.
53+
54+
### Step-by-Step Algorithm
55+
56+
1. **Initialization**:
57+
- Create a list `heights` of zeros with a length equal to the number of columns in the matrix.
58+
59+
2. **Iterate over Rows**:
60+
- For each row, update the `heights` where:
61+
- If `matrix[i][j] == '1'`, increment `heights[j]` by 1.
62+
- If `matrix[i][j] == '0'`, reset `heights[j]` to 0.
63+
64+
3. **Calculate Maximum Rectangle**:
65+
- For each updated `heights` array, use a stack to find the maximum rectangle area in the histogram.
66+
67+
### Python Solution
68+
69+
```python
70+
def maximalRectangle(matrix):
71+
if not matrix:
72+
return 0
73+
max_area = 0
74+
heights = [0] * len(matrix[0])
75+
76+
for row in matrix:
77+
for i in range(len(row)):
78+
if row[i] == '1':
79+
heights[i] += 1
80+
else:
81+
heights[i] = 0
82+
83+
max_area = max(max_area, largestRectangleArea(heights))
84+
85+
return max_area
86+
87+
def largestRectangleArea(heights):
88+
stack = []
89+
max_area = 0
90+
heights.append(0)
91+
92+
for i in range(len(heights)):
93+
while stack and heights[i] < heights[stack[-1]]:
94+
h = heights[stack.pop()]
95+
w = i if not stack else i - stack[-1] - 1
96+
max_area = max(max_area, h * w)
97+
stack.append(i)
98+
99+
heights.pop()
100+
return max_area
101+
```
102+
103+
### Java Solution
104+
```java
105+
import java.util.Stack;
106+
107+
class Solution {
108+
public int maximalRectangle(char[][] matrix) {
109+
if (matrix.length == 0) return 0;
110+
int maxArea = 0;
111+
int[] heights = new int[matrix[0].length];
112+
113+
for (char[] row : matrix) {
114+
for (int i = 0; i < row.length; i++) {
115+
heights[i] = row[i] == '1' ? heights[i] + 1 : 0;
116+
}
117+
maxArea = Math.max(maxArea, largestRectangleArea(heights));
118+
}
119+
120+
return maxArea;
121+
}
122+
123+
private int largestRectangleArea(int[] heights) {
124+
Stack<Integer> stack = new Stack<>();
125+
int maxArea = 0;
126+
int[] h = new int[heights.length + 1];
127+
System.arraycopy(heights, 0, h, 0, heights.length);
128+
129+
for (int i = 0; i < h.length; i++) {
130+
while (!stack.isEmpty() && h[i] < h[stack.peek()]) {
131+
int height = h[stack.pop()];
132+
int width = stack.isEmpty() ? i : i - stack.peek() - 1;
133+
maxArea = Math.max(maxArea, height * width);
134+
}
135+
stack.push(i);
136+
}
137+
138+
return maxArea;
139+
}
140+
}
141+
```
142+
143+
### C++ Solution
144+
```cpp
145+
#include <vector>
146+
#include <stack>
147+
#include <algorithm>
148+
149+
class Solution {
150+
public:
151+
int maximalRectangle(std::vector<std::vector<char>>& matrix) {
152+
if (matrix.empty()) return 0;
153+
int maxArea = 0;
154+
std::vector<int> heights(matrix[0].size(), 0);
155+
156+
for (const auto& row : matrix) {
157+
for (size_t i = 0; i < row.size(); ++i) {
158+
heights[i] = row[i] == '1' ? heights[i] + 1 : 0;
159+
}
160+
maxArea = std::max(maxArea, largestRectangleArea(heights));
161+
}
162+
163+
return maxArea;
164+
}
165+
166+
private:
167+
int largestRectangleArea(const std::vector<int>& heights) {
168+
std::stack<int> stack;
169+
int maxArea = 0;
170+
std::vector<int> h = heights;
171+
h.push_back(0);
172+
173+
for (size_t i = 0; i < h.size(); ++i) {
174+
while (!stack.empty() && h[i] < h[stack.top()]) {
175+
int height = h[stack.top()];
176+
stack.pop();
177+
int width = stack.empty() ? i : i - stack.top() - 1;
178+
maxArea = std::max(maxArea, height * width);
179+
}
180+
stack.push(i);
181+
}
182+
183+
return maxArea;
184+
}
185+
};
186+
```
187+
188+
### C Solution
189+
```c
190+
#include <stdio.h>
191+
#include <stdlib.h>
192+
#include <string.h>
193+
194+
int maximalRectangle(char** matrix, int matrixSize, int* matrixColSize) {
195+
if (matrixSize == 0) return 0;
196+
int maxArea = 0;
197+
int heights[*matrixColSize];
198+
memset(heights, 0, sizeof(heights));
199+
200+
for (int i = 0; i < matrixSize; i++) {
201+
for (int j = 0; j < *matrixColSize; j++) {
202+
heights[j] = matrix[i][j] == '1' ? heights[j] + 1 : 0;
203+
}
204+
maxArea = fmax(maxArea, largestRectangleArea(heights, *matrixColSize));
205+
}
206+
207+
return maxArea;
208+
}
209+
210+
int largestRectangleArea(int* heights, int size) {
211+
int maxArea = 0;
212+
int* stack = (int*)malloc((size + 1) * sizeof(int));
213+
int top = -1;
214+
heights[size] = 0;
215+
216+
for (int i = 0; i <= size; i++) {
217+
while (top != -1 && heights[i] < heights[stack[top]]) {
218+
int height = heights[stack[top--]];
219+
int width = top == -1 ? i : i - stack[top] - 1;
220+
maxArea = fmax(maxArea, height * width);
221+
}
222+
stack[++top] = i;
223+
}
224+
225+
free(stack);
226+
return maxArea;
227+
}
228+
```
229+
230+
### JavaScript Solution
231+
```js
232+
var maximalRectangle = function(matrix) {
233+
if (matrix.length === 0) return 0;
234+
let maxArea = 0;
235+
let heights = new Array(matrix[0].length).fill(0);
236+
237+
for (let row of matrix) {
238+
for (let i = 0; i < row.length; i++) {
239+
heights[i] = row[i] === '1' ? heights[i] + 1 : 0;
240+
}
241+
maxArea = Math.max(maxArea, largestRectangleArea(heights));
242+
}
243+
244+
return maxArea;
245+
};
246+
247+
var largestRectangleArea = function(heights) {
248+
let stack = [];
249+
let maxArea = 0;
250+
heights.push(0);
251+
252+
for (let i = 0; i < heights.length; i++) {
253+
while (stack.length && heights[i] < heights[stack[stack.length - 1]]) {
254+
let height = heights[stack.pop()];
255+
let width = stack.length === 0 ? i : i - stack[stack.length - 1] - 1;
256+
maxArea = Math.max(maxArea, height * width);
257+
}
258+
stack.push(i);
259+
}
260+
261+
heights.pop();
262+
return maxArea;
263+
};
264+
```
265+
266+
### Conclusion
267+
This problem combines concepts from dynamic programming and stack-based approaches to efficiently calculate the largest rectangle containing only 1's in a binary matrix. By converting the problem to a series of histogram problems and using an optimized approach to find the largest rectangle in a histogram, we achieve a time-efficient solution.
268+
269+

0 commit comments

Comments
 (0)