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]1:
            res=max(res,heights[stack.pop()]*(l-stack[-1]-1))
        return res
            
            

你可能感兴趣的:(84. Largest Rectangle in Histogram)