https://oj.leetcode.com/problems/trapping-rain-water/
This problem uses the monotone queue to be able to solve the O (n) time. Maintains a sort of monotone queue in descending order. If Ai>a[que.front] means that you can use Que.front as the top to calculate the water once.
When starting from 0-n, be aware that there are elements in the queue. A monotone queue needs to be executed in reverse. But just go to the front location of the previous queue.
classSolution { Public: intTrapintA[],intN) {if(n==0)return 0; Queue<int>que; Que.push (0); intres=0; for(intI=1; i<n;i++){ intCur=A[i]; intt=A[que.front ()]; if(cur<t) Que.push (i); Else{ while(!Que.empty ()) {Res+=t-A[que.front ()]; Que.pop (); } que.push (i); } } if(Que.empty ())returnRes; intm=Que.front (); while(!que.empty ()) Que.pop (); Que.push (n-1); for(inti=n-2; i>=m;i--){ intCur=A[i]; intt=A[que.front ()]; if(cur<t) Que.push (i); Else{ while(!Que.empty ()) {Res+=t-A[que.front ()]; Que.pop (); } que.push (i); } } returnRes; }};
Leetcode-trapping rain water-raining Water-monotone queue application