[Stack]84. Largest Rectangle in Histogram

  • 分類(lèi):Stack
  • 時(shí)間復(fù)雜度: O(n)
  • 空間復(fù)雜度: O(n)

84. Largest Rectangle in Histogram

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.

image.png

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

image.png

The largest rectangle is shown in the shaded area, which has area = 10 unit.

Example:


Input: [2,1,5,6,2,3]

Output: 10

代碼1:

class Solution:
    def largestRectangleArea(self, heights: 'List[int]') -> 'int':
        if heights==None or len(heights)==0:
            return 0

        res=0
        j=0
        stack=[]
        left=0
        right=0
        heights.append(0)
        heights.insert(0,0)
        for i in range(0,len(heights)):
            if len(stack)==0 or heights[i]>heights[stack[-1]]:
                stack.append(i)
            else:
                right=i
                j=stack[-1]
                while len(stack)>1 and heights[stack[-1]]>heights[right]:
                    h=heights[stack.pop()]
                    left=stack[-1]
                    res=max(res,h*(right-left-1))
                stack.append(i)

        return res

代碼2:

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:

        res = 0
        if heights == None or len(heights)==0:
            return res

        stack = list()
        stack.append(-1)
        for i in range(len(heights)):
            while(stack[-1]!=-1 and heights[stack[-1]]>=heights[i]):
                h = heights[stack.pop()]
                res = max(res, (i-stack[-1]-1)*h)
            stack.append(i)

        while (stack[-1]!=-1):
            h = heights[stack.pop()]
            res = max(res,(len(heights)-stack[-1]-1)*h)


        return res

討論:

1.看的youtube的籃子王的講解
2.我是兩邊直接加兩個(gè)0避免了還要比較邊界條件的情況???代碼可以更straight forward???
3.別忘了比完了之后那個(gè)地方的點(diǎn)是要加回去的orz
4.今天寫(xiě)代碼是看youtube上一個(gè)happygirl的博主。感覺(jué)思路比籃子王清楚。還是個(gè)單調(diào)遞增棧

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,872評(píng)論 0 10
  • 朋友得了本地名人一副書(shū)法墨寶,喜不自勝。 拿回家細(xì)細(xì)欣賞,喜愛(ài)之情難以言表。獨(dú)樂(lè)樂(lè)不如眾樂(lè)樂(lè),按捺不住內(nèi)心喜悅,拍...
    南雅之簡(jiǎn)閱讀 485評(píng)論 2 4
  • 我想寫(xiě)這篇文章已經(jīng)很久了,內(nèi)容早就想好,題目一直拿捏不準(zhǔn)。一開(kāi)始我想叫《Sensitive的男人Sex能力弱》,覺(jué)...
    惡毒姐閱讀 829評(píng)論 0 1

友情鏈接更多精彩內(nèi)容