Title Requirements: 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!
The code is as follows:
classSolution { Public: intTrapintA[],intN) {intMaxidx =0; intWater =0; //find the longest plank, set as Maxidx for(inti =1; I < n; i++){ if(A[i] >A[maxidx]) {Maxidx=i; } } intmax = a[0]; //left approximation for(inti =1; i < Maxidx; i++){ if(Max <A[i]) Max=A[i]; //The left side (max) and the right (highest) are taller than the wood, so you can put//Max-The length of the plank of water ElseWater+ = max-A[i]; } //Right approximationmax = A[n-1]; for(inti = n-2; I >= maxidx; i--){ if(Max < a[i]) max =A[i]; ElseWater + = max-A[i]; } returnwater; }};
Leetcode 042 trapping Rain water