0
点赞
收藏
分享

微信扫一扫

leetcode第84题柱状图中最大的矩形--单调栈

楠蛮鬼影 2022-02-18 阅读 68

其实最开始是想写DP的也写出来了,但有一个测试用例全他妈是1,真的恶心,然后就用单调栈

class Solution(object):
  def largestRectangleArea(self, heights):
    """
    :type heights: List[int]
    :rtype: int
    就是需要用栈,用dp的话空间真的不够
    栈顶保存高度和进去时候的坐标(累计宽度)
    :stack[0]heights
    :stack[1]start_index
    """
    heights.append(0)
    ans=0
    stack_temp=[[heights[0],0]]
    for i in range(1,len(heights)):
      temp=[0,i]
      while stack_temp and stack_temp[-1][0]>heights[i]:
        temp=stack_temp.pop(-1)
        ans=max(ans,temp[0]*(i-temp[1]))
      if not stack_temp or stack_temp[-1][0]<heights[i]:
        stack_temp.append([heights[i],temp[1]])
    return ans
举报

相关推荐

0 条评论