Skip to content

Commit 0e9f82f

Browse files
Sync LeetCode submission Runtime - 39 ms (5.00%), Memory - 17.3 MB (92.98%)
1 parent aed2a49 commit 0e9f82f

2 files changed

Lines changed: 62 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<p>Given a <code>rows x cols</code>&nbsp;binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, find the largest rectangle containing only <code>1</code>&#39;s and return <em>its area</em>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/14/maximal.jpg" style="width: 402px; height: 322px;" />
6+
<pre>
7+
<strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]]
8+
<strong>Output:</strong> 6
9+
<strong>Explanation:</strong> The maximal rectangle is shown in the above picture.
10+
</pre>
11+
12+
<p><strong class="example">Example 2:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> matrix = [[&quot;0&quot;]]
16+
<strong>Output:</strong> 0
17+
</pre>
18+
19+
<p><strong class="example">Example 3:</strong></p>
20+
21+
<pre>
22+
<strong>Input:</strong> matrix = [[&quot;1&quot;]]
23+
<strong>Output:</strong> 1
24+
</pre>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li><code>rows == matrix.length</code></li>
31+
<li><code>cols == matrix[i].length</code></li>
32+
<li><code>1 &lt;= rows, cols &lt;= 200</code></li>
33+
<li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li>
34+
</ul>
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public:
3+
int maximalRectangle(vector<vector<char>>& matrix) {
4+
int n = matrix.size();
5+
int m = matrix[0].size();
6+
7+
vector<vector<int>> ones(n, vector<int>(m, 0));
8+
for (int i=0; i<n; i++) {
9+
ones[i][0] = matrix[i][0] - '0';
10+
for (int j=1; j<m; j++) ones[i][j] = (matrix[i][j] == '1' ? ones[i][j-1] + 1 : 0);
11+
}
12+
13+
int ans = 0;
14+
for (int i=0; i<n; i++) {
15+
for (int j=0; j<m; j++) {
16+
int width = 1e9;
17+
int height = 0;
18+
for (int k=i; k>=0; k--) {
19+
height++;
20+
width = min(width, ones[k][j]);
21+
ans = max(ans, height * width);
22+
}
23+
}
24+
}
25+
26+
return ans;
27+
}
28+
};

0 commit comments

Comments
 (0)