Leetcode-trapping rain water-raining Water-monotone queue application

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.