首页 > 其他 > 详细

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

时间:2019-05-15 01:06:03      阅读:111      评论:0      收藏: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

 

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

原文:https://www.cnblogs.com/Johnsonxiong/p/10865898.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!