[LC] 84. Largest Rectangle in Histogram

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

 


Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

 


The largest rectangle is shown in the shaded area, which has area = 10 unit.

 

Example:

Input: [2,1,5,6,2,3]
Output: 10

Solution 1: O(N^2) LTE
class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        if not heights:
            return 0
        res = -1
        for i, height in enumerate(heights):
            min_height = height
            res = max(res, min_height)
            for j in range(i + 1, len(heights)):
                min_height = min(min_height, heights[j])
                res = max(res, (j - i + 1) * min_height)
        return res

 

Solution 2: O (N)

 class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        if not heights:
            return 0
        res, index  = 0, 0
        stack = []
        while index <= len(heights):
            cur = 0 if index == len(heights) else heights[index]
            if not stack or cur >= heights[stack[-1]]:
                stack.append(index)
                index += 1
            else:
                height = heights[stack.pop()]
                # make sure left and right index are correct
                right = index - 1
                left = 0 if not stack else stack[-1] + 1
                res = max(res, (right - left + 1) * height)
        return res

 

 

Guess you like

Origin www.cnblogs.com/xuanlu/p/11828789.html