How does the largest rectangle in histogram problem use a monotonic stack?
LeetCode Patterns Flashcards: Stack, Monotonic Stack, Valid Parentheses, Next Greater
Аудио-карточка · 0:30Nortren·
How does the largest rectangle in histogram problem use a monotonic stack?
0:30
Maintain an increasing monotonic stack of bar indices. When a bar shorter than the stack top is encountered, the taller bars can no longer extend right, so pop them and calculate their rectangle area. The width extends from the current index back to the new stack top plus one. Track the maximum area found. After processing all bars, pop remaining bars using the array length as the right boundary. This runs in O of n time. The key insight is that each bar's maximum rectangle is bounded by the first shorter bar on its left and right, and the monotonic stack efficiently finds both boundaries.
neetcode.io