84. 柱状图中最大的矩形
分治法,但PYTHON还是超时,因为有个巨长的有序测试数据,此时分治变O(N2)过不去。。
class Solution:
def largestRectangleArea(self, heights) -> int:
return recur(heights,0,len(heights))
def recur(heights,le,ri):
if le>=ri:
return 0
mi=le
for i in range(le,ri):
if heights[i]<heights[mi]:
mi=i
print(le,mi,ri)
cur_area=(ri-le)*heights[mi]
if mi>le and mi+1<ri:
return max(recur(heights,le,mi),recur(heights,mi+1,ri),cur_area)
if mi>le:
return max(recur(heights,le,mi),cur_area)
if mi+1<ri:
return max(recur(heights,mi+1,ri),cur_area)
return cur_area
递增栈,主要看的这篇博客
class Solution:
def largestRectangleArea(self, heights) -> int:
stack=list()
i,res=0,0
while i<len(heights):
if not stack or heights[stack[-1]]<=heights[i]:
stack.append(i)
i+=1
else:
k=stack.pop()
res=max(heights[k]*((i-stack[-1]-1) if stack else i),res)
while stack:
k=stack.pop()
res=max(heights[k]*((i-stack[-1]-1) if stack else i),res)
return res
进击的小🐴农