leetcode 每日一题 85. 最大矩形
Posted nil_f
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 每日一题 85. 最大矩形相关的知识,希望对你有一定的参考价值。
单调栈
思路:
遍历每一行,用dp记录每行元素与之前行所能形成的柱形图的高,之后用单调栈的方式找到每行最大矩形面积,单调栈方式参考84.柱形图中最大的矩形
代码:
class Solution: def largestRectangleArea(self,heights: List[int]) -> int: n = len(heights) left, right = [0] * n, [n] * n mono_stack = list() for i in range(n): while mono_stack and heights[mono_stack[-1]] >= heights[i]: right[mono_stack[-1]] = i mono_stack.pop() left[i] = mono_stack[-1] if mono_stack else -1 mono_stack.append(i) ans = max((right[i] - left[i] - 1) * heights[i] for i in range(n)) if n > 0 else 0 return ans def maximalRectangle(self, matrix: List[List[str]]) -> int: if not matrix: return 0 maxarea = 0 dp = [0] * len(matrix[0]) for i in range(len(matrix)): for j in range(len(matrix[0])): dp[j] = dp[j] + 1 if matrix[i][j] == \'1\' else 0 maxarea = max(maxarea, self.largestRectangleArea(dp)) return maxarea
动态规划
思路:
用数组left记录每一行中每个元素的左边界值,数组right记录每一行中每个元素的右边界值,height记录每一行中每个元素的高,遍历每一行刷新3个数组的值,同时记录最大面积值。
代码:
class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: if not matrix: return 0 m = len(matrix) n = len(matrix[0]) left = [0] * n right = [n] * n height = [0] * n maxarea = 0 for i in range(m): cur_left, cur_right = 0, n for j in range(n): if matrix[i][j] == \'1\': height[j] += 1 else: height[j] = 0 for j in range(n): if matrix[i][j] == \'1\': left[j] = max(left[j], cur_left) else: left[j] = 0 cur_left = j + 1 for j in range(n-1, -1, -1): if matrix[i][j] == \'1\': right[j] = min(right[j], cur_right) else: right[j] = n cur_right = j for j in range(n): maxarea = max(maxarea, height[j] * (right[j] - left[j])) return maxarea
以上是关于leetcode 每日一题 85. 最大矩形的主要内容,如果未能解决你的问题,请参考以下文章