"Leetcode" trapping Rain water

Source: Internet
Author: User

Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much WA ter It is the able to trap after raining.

For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1] , return 6 .

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image!

Find the longest plank in the position, approaching it from the left and right side respectively.

In the left approximation process:

If the length of a plank is less than the maximum length that has been traversed Max, i.e. max> the plank <maxidx, it is possible to store max-the amount of water in the plank's length (on each side of the board longer than it).

If the length of a plank is greater than the maximum length that has been traversed Max, i.e. max< the plank <maxidx, no water can be stored in the board position (since there is only one plank (MAXIDX) longer than the left and right sides). Updates the max value.

The right approximation process is similar to the left.

1 classSolution {2  Public:3     intTrapintA[],intN) {4          5         if(n==0)return 0;6          7         inti;8         intmaxindex=0;9         intamax=a[0];Ten          One          for(i=1; i<n;i++) A         { -             if(amax<A[i]) -             { theamax=A[i]; -maxindex=i; -             } -         } +           -         intcurmax=a[0]; +         intTotalwater=0; A           at          for(i=1; i<maxindex;i++) -         { -             if(A[i]<curmax) totalwater+=curmax-A[i]; -             Elsecurmax=A[i]; -         } -           incurmax=a[n-1]; -          for(i=n-2; i>maxindex;i--) to         { +             if(A[i]<curmax) totalwater+=curmax-A[i]; -             Elsecurmax=A[i]; the         } *           $         returnTotalwater;Panax Notoginseng     } -};

"Leetcode" trapping Rain water

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.