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