84. Largest Rectangle in Histogram

class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        #O(n) solution 
        #for each rectangle, calculate the max area formed with its height h(with h being the smallest rectangle) 
        #then get the max of all the results
        #get the index of the first smaller rectangle to its left: left_index
        #and the index of the first smaller rectangle to its right: right_index
        #use mono increasing stack 
        if not heights: return 0 
        l=len(heights)
        if l==1: return heights[0]
        #store the index of the rectangles
        #stack is mono increasing, therefore we can easily locate the most adjacent index
        stack=[-1,0]
        res=0
        for i in range(1,l):
            while len(stack)>1 and  heights[i]<heights[stack[-1]]:
                res=max(res,heights[stack.pop()]*(i-stack[-1]-1))
            stack.append(i)
            
        while len(stack)>1:
            res=max(res,heights[stack.pop()]*(l-stack[-1]-1))
        return res
            
            
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容