Largest Rectangle in histogram
High Level:
Two Methods:
LeftMost rightMost:
Traverse through three times.
Find longest non-descending sequence left and right.
Calculate middle out for each tile.
Clearing the debris:
use a stack of indexes to keep track ascending sequences
rule of traversal:
while ascending, add to stack
on descend:
while top of stack is >= cur index:
pop the top, that's the height
find left bound: if the stack is empty: 0, else its the new top of the stack
check cur max against height * (i - left - 1)
add cur index to stack
Details:
WHY ASCENDING SEQUENCE?
ex: 12342
^
cur
once we pop out all heights greater or equal to cur. We are guaranteed that cur can extend until the new top index.
Why pop equal size tiles?
for cases like 2 2 1:
The first 2 needs to be popped, because the implicit left bound of each tile is tracked by the index at the top of the stack. (ref: line 10) Therefore without popping the 2 at index 0, we would get two 2x1 rectangles instead of one 2x2 rectangle.
Last updated
Was this helpful?