0
点赞
收藏
分享

微信扫一扫

[LeetCode]Maximal Rectangle


Question
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Return 6.

本题难度Hard。

【复杂度】
时间 O(MN) 空间 O(MN)

【思路】
本题可以建模成寻找最大矩形问题(​​[LeetCode]Largest Rectangle in Histogram​​)。要求最大的矩形,实际上可以将矩阵的每一行,转化为直方图,而直方图的每个竖条的数字,就是该行对应坐标正上方有多少个连续的1。而第一行的数值就是本身。如果原始矩阵中遇到​​'0'​​,则累加中断,重新置0。

【代码】

public class Solution {
public int maximalRectangle(char[][] matrix) {
//require
int m=matrix.length;
if(m<1)
return 0;
int n=matrix[0].length;
int ans=0;
int[][] dp=new int[m][n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++){
if(i==0)
dp[i][j]=matrix[i][j]-'0';
else
dp[i][j]=matrix[i][j]=='0'?0:matrix[i][j]-'0'+dp[i-1][j];
}
//invariant
for(int[] heights:dp)
ans=Math.max(largestRectangleArea(heights),ans);
//ensure
return ans;
}
private int largestRectangleArea(int[] heights){
//require
int size=heights.length;
Stack<Integer> stack=new Stack<>();
int i=0,ans=0;
//invariant
while(i<size||(i==size&&!stack.isEmpty())){
if(i<size&&(stack.isEmpty()||heights[i]>=heights[stack.peek()]))
stack.push(i++);
else{
int top=heights[stack.pop()];
int rectangle=!stack.isEmpty()?top*(i-stack.peek()-1):top*i;
ans=Math.max(rectangle,ans);
}
}
//ensure
return ans;
}
}


举报

相关推荐

0 条评论