title :
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!
Code :
classSolution { Public: intTrap (vector<int>&height) { //Non valid input intLen =height.size (); if(len<=2)return 0; //Initial intleft_max[height.size ()]; intright_max[height.size ()]; left_max[0] =0; Right_max[len-1] =0; //get Left_max and Right_max for(inti =1; i < Len; ++i) {Left_max[i]= Std::max (left_max[i-1], height[i-1]); Right_max[len-i-1] = Std::max (Right_max[len-i], height[len-i]); } //Calculate the sum intsum =0; for(inti =0; i < Len; ++i) {inth =std::min (Left_max[i], right_max[i]); if(h>Height[i]) {Sum+ = hHeight[i]; } } returnsum; }};
Tips:
1. Traverse, obtain the highest left and right side of each position, and select a smaller height on the left and right, minus the height of the position, which is the amount of water available.
2. Note the handling of some extreme cases
"Trapping Rain Water" CPP