Monotonic stack
A monotonic stack is a solution to such a class of problems
Given n numbers, ask who is the first smaller number to the left of each number
If it is directly violent, the worst case must be $O(n^2)$, but the monotonic stack can solve this kind of problem in $O(n)$ time
accomplish
A monotonic stack, Gu Ming thinks, is to maintain a monotonic stack. As for whether it is monotonically increasing or monotonically decreasing, it depends on the topic.
For the above problem, we need to maintain a monotonically increasing sequence
When adding an element, if the current element is smaller than the top element of the stack, the top element of the stack is continuously popped until the entire stack is monotonic
Then the first smaller than it to the left of the position is the top of the stack
The above is too abstract
For example, we have a sequence $2,4,3,5,2$
Let $ans[i]$ denote the answer at position $i$
$2$ is added to the sequence, at this time the sequence is $2$, $ans[1]=0$
$4$ is added to the sequence, at this time the sequence is $2,4$, $ans[2]=2$
$3$ is added to the sequence, we find that if $3$ is directly added to the sequence, the sequence will not satisfy the monotonicity, so first delete $4$, then add $3$, at this time the sequence is $2,3$, $ans[3] =2$
$5$ is added to the sequence, at this time the sequence is $2,3,5$, $ans[4]=5$
$2$ is added to the sequence, $2,3,5$ is deleted, and $2$ is added. At this time, the sequence is $2$, and $ans[5]=0$
Consider that each element is added/removed at most once, so the time complexity is $O(n)$
As for why, it seems quite obvious, that is to use monotonicity
example
It's all water
Some difficulty, using the idea of monotonic stack