码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 每日一题 85. 最大矩形

时间:2020-06-16 13:10:33      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:mamicode   代码   单调栈   else   div   lan   href   http   面积   

技术图片

单调栈

思路:

遍历每一行,用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. 最大矩形

标签:mamicode   代码   单调栈   else   div   lan   href   http   面积   

原文地址:https://www.cnblogs.com/nilhxzcode/p/13140286.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!