代码改变世界

[LeetCode] 84. Largest Rectangle in Histogram_Hard tag: stack

2019-05-15 00:20  Johnson_强生仔仔  阅读(220)  评论(0编辑  收藏  举报

 

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

这个题目brute force ,O(n ^ 2), 两个for loop,最坏情况,可能要到n ^3。

但是利用stack,可以达到 O(n)

利用stack,然后维护一个strict increasing stack,每次将height的index 放进stack里面,保持height能够是strict increase的,这样就能找到针对每一个height,可以找到往左第一个比它矮的木头的index,同时右边的第一个最矮的木头的index,然后将height *(index_right - index_left - 1), 跟ans比较来更新ans,最后返回ans。

Code

class Solution:
    def largestRetangle(self, heights: List[int]) -> int:
        ans, stack = 0, [] # note that indexes are in stack instead of height
        for index, height in enumerate(heights + [0]): # add 0 in the end ,保证将所有的height都走一遍
            while stack and heights[stack[-1]] >= height:
                index_pop = stack.pop()
                width = index - stack[-1] - 1 if stack else index # 当左边没有比它小的情况
                ans = max(ans, width * heights[index_pop])
            stack.append(index)
        return ans