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