leetcode: 84. Largest Rectangle in Histogram

来源:互联网 发布:海知智能孙胜男 编辑:程序博客网 时间:2024/06/14 09:30

Q

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.

For example,
Given heights = [2,1,5,6,2,3],
return 10.

AC

class Solution(object):    def largestRectangleArea(self, heights):        """        :type heights: List[int]        :rtype: int        """        heights.insert(0,0)        heights.append(0)        stack = []        maxarea = 0        for i, height in enumerate(heights):            if not stack or heights[stack[-1]]<=height:                stack.append(i)            else:                while stack and heights[stack[-1]]>height:                    maxarea = max(maxarea, heights[stack[-1]]*(i-stack[-2]-1))                    stack.pop()                stack.append(i)        right = stack[-1]        stack.pop()        while len(stack)>1:            offset = right-stack[-1]            maxarea = max(maxarea, heights[stack[-1]]*offset)            stack.pop()        return maxarea# Time:  O(n)# Space: O(n)class Solution2(object):    def largestRectangleArea(self, height):        increasing, area, i = [], 0, 0        while i <= len(height):            if not increasing or (i < len(height) and height[i] > height[increasing[-1]]):                increasing.append(i)                i += 1            else:                last = increasing.pop()                if not increasing:                    area = max(area, height[last] * i)                else:                    area = max(area, height[last] * (i - increasing[-1] - 1 ))        return areaif __name__ == "__main__":    assert Solution().largestRectangleArea([2, 0, 2]) == 2    assert Solution().largestRectangleArea([2, 1, 5, 6, 2, 3]) == 10


阅读全文
0 0
原创粉丝点击