Idea
The key idea for my O(n) algorithm is keeping two stacks named position_stack and height_stack while traverse. The definition of stacks is defined in following:(Pay attention the size of the two stacks should keep consistent)
Let the original height array be heights
, A equal position_stack[i]
, B equal height_stack[i]
. This notation means the max height of the qualified rectangle starting at index A(Ending at the current cursor index
) in heights
is B.
Code
The stack has a little trick in my implementation. I used a sentinel node which is less then all the normal heights and indexed at -1 as the first item in the stacks, to simplify the code when handling the corner case.
1 | class Solution: |