class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
#O(n) solution
#for each rectangle, calculate the max area formed with its height h(with h being the smallest rectangle)
#then get the max of all the results
#get the index of the first smaller rectangle to its left: left_index
#and the index of the first smaller rectangle to its right: right_index
#use mono increasing stack
if not heights: return 0
l=len(heights)
if l==1: return heights[0]
#store the index of the rectangles
#stack is mono increasing, therefore we can easily locate the most adjacent index
stack=[-1,0]
res=0
for i in range(1,l):
while len(stack)>1 and heights[i]<heights[stack[-1]]:
res=max(res,heights[stack.pop()]*(i-stack[-1]-1))
stack.append(i)
while len(stack)>1:
res=max(res,heights[stack.pop()]*(l-stack[-1]-1))
return res
84. Largest Rectangle in Histogram
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 首先,可以使用暴力破解法,以每一个数字作为高度,随后遍历找出长度,最后进行大小的匹配即可,但是由于是O(n^2)复...
- 题目: https://leetcode.com/problems/largest-rectangle-in-hi...
- 第一版:超时,双层循环。 看了看tag,用栈的话,加以优化。Largest Rectangle in Histog...
- Given n non-negative integers representing the histogram'...
- Given n non-negative integers representing the histogram'...