leetcode85

时间:2024-11-16 22:35:25
 class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0; int[] height = new int[matrix[0].length];
for(int i = 0; i < matrix[0].length; i ++){
if(matrix[0][i] == '1') height[i] = 1;
}
int result = largestInLine(height);
for(int i = 1; i < matrix.length; i ++){
resetHeight(matrix, height, i);
result = Math.max(result, largestInLine(height));
} return result;
} private void resetHeight(char[][] matrix, int[] height, int idx){
for(int i = 0; i < matrix[0].length; i ++){
if(matrix[idx][i] == '1') height[i] += 1;
else height[i] = 0;
}
} public int largestInLine(int[] height) {
if(height == null || height.length == 0) return 0;
int len = height.length;
Stack<Integer> s = new Stack<Integer>();
int maxArea = 0;
for(int i = 0; i <= len; i++){
int h = (i == len ? 0 : height[i]);
if(s.isEmpty() || h >= height[s.peek()]){
s.push(i);
}else{
int tp = s.pop();
maxArea = Math.max(maxArea, height[tp] * (s.isEmpty() ? i : i - 1 - s.peek()));
i--;
}
}
return maxArea;
}
}

参考:https://leetcode.com/problems/maximal-rectangle/discuss/29055/My-java-solution-based-on-Maximum-Rectangle-in-Histogram-with-explanation

补充一个python的实现:

 class Solution:
def maximalRectangle(self, matrix: 'List[List[str]]') -> int:
if matrix == None:
return 0
row = len(matrix)
if row == 0:
return 0
column = len(matrix[0])
if column == 0:
return 0
heights = [0] * column
for i in range(column):
if matrix[0][i] == '':
heights[i] = 1
result = self.largestRectangleArea(heights)
for i in range(1,row):
self.resetHeight(matrix,heights,i)
result = max(result,self.largestRectangleArea(heights))
return result def largestRectangleArea(self, heights: 'List[int]') -> int:
heights.append(0)#默认最后补充一个0,方便统一处理
n = len(heights)
s = []
max_area = 0#最大面积
tp = 0#栈顶索引
area_with_top = 0#临时面积
i = 0
while i < n:
if len(s) == 0 or heights[s[-1]] <= heights[i]:
s.append(i)#栈内记录的是高度递增的索引
i += 1
else:#遇到了高度比当前栈顶元素低的元素时,
tp = s.pop(-1)#清算栈内的元素的高度
if len(s) == 0:
area_with_top = heights[tp] * i#栈内没有元素,则宽度是i
else:#高度是栈顶元素,宽度是i - 1 - 前一个栈顶元素的索引
area_with_top = heights[tp] * (i - s[-1] - 1)
max_area = max(max_area,area_with_top)#更新最大值
return max_area def resetHeight(self,matrix,height,idx):
for i in range(len(matrix[0])):
if matrix[idx][i] == '':
height[i] += 1
else:
height[i] = 0

思路分析:本题以leetcode 84为基础,相当于计算一个柱状图中最大的面积。

leetcode85

如图上所示,对于数组[2,1,5,6,2,3]其最大面积是10。在此基础上,将本题转化为row次的柱状图计算:

leetcode85按照行“递增”计算4次。

1、leetcode85[1,0,1,0,0],最大面积是1

2、leetcode85[1+1,0,1+1,1,1] => [2,0,2,1,1],最大面积是3

3、leetcode85[1+1+1,1,1+1+1,1+1,1+1] => [3,1,3,2,2],最大面积是6

4、leetcode85[1+1+1+1,0,0,1+1+1,0] => [4,0,0,3,0],最大面积是4

经过这4次循环,计算完毕。第3次得到的结果,是这个二维数组可构成的最大面积6。

相关文章