84. 柱状图中最大的矩形(每日一题,hard难度)

100天leetcode每日两题(day2)

大概思路就是要求的面积肯定在能完全包含第k个柱子的矩形面积中选,这里有6个柱子就需要求6次,例如:

100天leetcode每日两题(day2)100天leetcode每日两题(day2)

柱子越矮,覆盖面积越宽越窄,柱子越高,覆盖面积越高越细,所以柱子高度适中最好:

100天leetcode每日两题(day2)

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        stack = [-1]
        max_res = 0
        for i in range(len(heights)):
            while len(stack) > 1 and heights[i] <= heights[stack[-1]]:
                max_res = max(max_res, heights[stack.pop()] * (i - stack[-1] - 1))  
            stack.append(i)
        for i in range(len(stack)-1):
            max_res = max(max_res, heights[stack.pop()]*(len(heights)-1-stack[-1]))
        return max_res

一个个找,最容易理解,但是时间复杂度太高了,所以用单调栈优化一下时间复杂度(如果左边的柱子比右边的矮,那么比左边矮的柱子肯定也比右边矮):

 

 


 

相关文章: