[Leetcode]84. Largest Rectangle in Histogram

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.
histogram

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

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.

python solution

class Solution:
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        stk = []
        res = 0
        if len(heights) == 1:
            return heights[0]
        if len(heights) == 0:
            return 0
        heights.append(0)
        for i,h in enumerate(heights):
            while stk and heights[stk[-1]] > h:
                index = stk.pop()
                if stk:
                    r = stk[-1]
                else:
                    r = -1
                res = max((i-r-1)*heights[index],res)
            stk.append(i)
        return res

解答过程:
step1:找到最大的矩形,自己在纸上画几个例子就应该知道问题可先转化为找到每条bar的左边界(左边第一个比它小的bar)与右边界(右边第一个比它小的bar).

|右边界-左边界|*bar的高度 = 该bar能构造的最大矩形

step2:直觉上,涉及数组中的数之间大小的关系的题目,大多数都可以用一次遍历解决.即O(n)的时间复杂度.

step3:

猜你喜欢

转载自blog.csdn.net/m0_37422289/article/details/79727844
今日推荐