LeetCode 84. 柱状图中最大的矩形 Python

给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。

求在该柱状图中,能够勾勒出来的矩形的最大面积。

以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]

图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。

 

示例:

输入: [2,1,5,6,2,3]
输出: 10

思路:利用单调栈,这个栈里面只存储递增或者递减的数组(即这个柱状图的下标)

Python:

class Solution:
    def largestRectangleArea(self, heights):
        
        """
        :type heights: List[int]
        :rtype: int
        """
        
        i = 0
        max_value = 0
        stack = []
        heights.append(0)
       
        while i < len(heights):
            
            if len(stack) == 0 or heights[stack[-1]] <= heights[i]:
                stack.append(i)
                i += 1
            else:
                now_idx = stack.pop()
                
                if len(stack) == 0:
                    max_value = max(max_value,i * heights[now_idx])
                else:                    
                    max_value = max(max_value,(i- stack[-1] -1) * heights[now_idx])
                    
        return max_value
                               

 

你可能感兴趣的:(LeetCode 84. 柱状图中最大的矩形 Python)