How does the daily temperatures problem use a monotonic stack?
LeetCode Patterns Flashcards: Stack, Monotonic Stack, Valid Parentheses, Next Greater
Аудио-карточка · 0:27Nortren·
How does the daily temperatures problem use a monotonic stack?
0:27
Maintain a stack of indices where corresponding temperatures form a decreasing sequence. For each new day, while the stack is not empty and the current temperature is higher than the temperature at the stack top index, pop the index and record the difference between the current index and the popped index as the number of days to wait. Then push the current index. Elements remaining on the stack after processing have no warmer future day, so their answer is zero. This runs in O of n time because each index is pushed and popped exactly once.
neetcode.io