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 Marcosfor Contributing This image!
The title is as above. The last hard problem of the holiday, first put the code implemented earlier, but also to simplify
1 classSolution {2 Public:3 intTrap (vector<int>&height) {4 intsum=0;5 for(intI=0; Ii) {6 for(intj=i+1; Jj) {7 if(height[j]>=Height[i]) {8sum+=height[i]* (j-i-1);9 //can be optimized, m->iTen for(intm=i+1; m<j;++m) { Onesum-=Height[m]; A } -i=j-1; - Break; the } - if(J==height.size ()-1){ - intmax=height[i+1]; - intmax_i=i+1; + for(intn=max_i+1; NN) { - if(height[n]>max) { +max=Height[n]; AMax_i=N; at } - } -sum+=height[max_i]* (max_i-i-1); - for(intm=i+1; m<max_i;++m) { -sum-=Height[m]; - } ini=max_i-1; - } to } + - } the returnsum; * } $};
Leetcode42. Trapping Rain Water