The meaning of monotonic stack: record (element i traverses from left (right traverse) the first element k that is less than or greater than) subscript
Vernacular: (eligible) and (element k closest to element i) subscript
The condition here means: larger than element i, or smaller than element i
The maintenance significance of the monotonic stack: ensure that the bottom f of the stack is the minimum value of the interval [0, i), and ensure that all elements of the stack are the first minimum value of [0, i), the second minimum value......
Maintained core code:
while(!p1.empty() && t[p1.top()] >= t[i]) p1.pop();
int ml[mmax]; stack<int> p1; for(int i = 1 ; i <= n ; i ++){ while(!p1.empty() && t[p1.top()] >= t[i]) p1.pop(); if(p1.empty()) ml[i] = 0; else ml[i] = p1.top(); p1.push(i); }
Each element can only be pushed onto the stack once, and the corresponding element can only be popped once at most.
That is, the algorithm complexity: O(N)*O(1) = O(N)
for(int i = 1 ; i<= n ; i++){
O(1);
}