85. Maximal Rectangle

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      

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值