84. Largest Rectangle in Histogram ( mono increasing stack

https://leetcode.com/problems/largest-rectangle-in-histogram/

naive

T: O(n^2)

mono stack

h = heights[stack.pop()]; => 7

2 - 0 - 1

i - stack.peek() - 1

area = 7 * (2 - 0 - 1)

O(n), O(n)

readable version

i = heights.lenght , cur 設定成 -1, 用意在讓stack剩下的 pop()完(退棧)

heights[stack.peek()] >= cur => 一定 >= -1,

stack 空的時候, leftBound = -1, or stack.peek()

這樣才能算到比較低的那根到左邊界所有的面積

2. 2

1

2會先退掉 (1比較小

2

1

到底才開始退(右邊界-1了

2退掉

1退掉, 此時stack 空了, 代表可以算左邊界 -1了

newest version

Last updated

Was this helpful?