LeetCode
Explore
Problems
Mock
Contest
Articles
Discuss
Store
Premium
New Playground
lifeqiuzhi520
833 27
85. Maximal Rectangle
DescriptionHintsSubmissionsDiscussSolution
Pick One
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6
Seen this question in a real interview before? YesNo
Difficulty:Hard
Total Accepted:97.6K
Total Submissions:316.3K
Contributor:LeetCode
Subscribe to see which companies asked this question.
Related Topics
ArrayHash TableDynamic ProgrammingStack
Similar Questions
Largest Rectangle in HistogramMaximal Square
Java
,
1
class Solution {
2
public int maximalRectangle(char[][] matrix) {
3
if(matrix.length == 0 || matrix[0].length == 0){
4
return 0;
5
}
6
int [] height = new int[matrix[0].length];
7
for(int i = 0;i < height.length;i++){
8
if(matrix[0][i]=='1'){
9
height[i] = 1;
10
}else{
11
height[i] = 0;
12
}
13
}
14
int max = findMaxArea(height);
15
for(int i = 1;i < matrix.length;i++){
16
for(int j = 0;j < height.length;j++){
17
if(matrix[i][j]=='1'){
18
height[j] += 1;
19
}else
20
{
21
height[j]= 0;
22
}
23
24
}
25
max = Math.max(max,findMaxArea(height));
26
}
27
return max;
28
29
30
}
31
int findMaxArea(int height[]){
32
int maxArea = 0;
33
Stack<Integer> stack = new Stack<Integer>();
34
for(int i = 0;i < height.length+1;i++){
35
int h = i == height.length?0:height[i];
36
if(stack.isEmpty()||h>=height[stack.peek()]){
37
stack.push(i);
38
}else{
39
int top = stack.pop();
40
maxArea = Math.max(maxArea,height[top]*(stack.isEmpty()?i:i-1-stack.peek()));
41
i--;
42
}
43
}
44
return maxArea;
45
}
46
}
Custom Testcase( Contribute )
Run Code Submit Solution
Submission Result: Accepted More Details
Next challenges: Maximal Square
Share your acceptance!
Notes
|||
Type here...(Markdown is enabled)
Copyright © 2018 LeetCode Contact Us | Jobs | Students | Frequently Asked Questions | Terms of Service | Privacy Policy