LeetCode 85 最大矩形

编程入门 行业动态 更新时间:2024-10-24 12:31:59

LeetCode 85 最大<a href=https://www.elefans.com/category/jswz/34/1759498.html style=矩形"/>

LeetCode 85 最大矩形

给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例 1:


输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:6
解释:最大矩形如上图所示。

示例 2:

输入:matrix = []
输出:0

示例 3:

输入:matrix = [["0"]]
输出:0

示例 4:

输入:matrix = [["1"]]
输出:1

示例 5:

输入:matrix = [["0","0"]]
输出:0
 

提示:

rows == matrix.length
cols == matrix[0].length
0 <= row, cols <= 200
matrix[i][j] 为 '0' 或 '1'

解题思路:

单调栈

最大矩形 - 最大矩形 - 力扣(LeetCode)

LeetCode 84 柱状图中最大的矩形_麦格芬230的博客-CSDN博客

Python代码:

class Solution:def maximalRectangle(self, matrix: List[List[str]]) -> int:m, n = len(matrix), len(matrix[0])heights = [0] * nres = 0for i in range(m):for j in range(n):if matrix[i][j] == '1':heights[j] += 1else:heights[j] = 0res = max(res, self.largestRectangleArea(heights))return resdef largestRectangleArea(self, heights):heights = [0] + heights + [0]n = len(heights)stack = [0]ans = 0for i in range(1, n):while heights[i] < heights[stack[-1]]:height = heights[stack.pop()]width = i - stack[-1] - 1ans = max(ans, height * width)stack.append(i)return ans

更多推荐

LeetCode 85 最大矩形

本文发布于:2024-02-27 06:12:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1705484.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩形   LeetCode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!