[LeetCode] Largest Rectangle in Histogram
This problem is similar to Trapped Water.
Initial thought will be for each bar, try to find the bounds of right and left
However this takes O(n^2) way too long
Instead of trying to find each time, we can use a stack to memorize the history height and position
We only calculate the size when we see a bar the lower than previous ones
Because we know that it’s impossible for the previous height to sustain
However there’s one thing to remember:
When we pop the previous elements, keep the position in stack
Because although the height cannot be sustained, the future rectangle can still count it.
1 | class Solution: |