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 .
I think this problem is similar to the question of buying stocks and the maximum water storage, and I feel that I should do it in a divide-and-conquer way.
But not ... This is the answer given by someone else.
The idea is too ingenious ... Ah ....
An O (n) solution are to consider each bar at a time, we can see this, for each bar, the water itself can trap depends on th e max height on it left and right, e.g. If current bar was of Height 2, the max height on it left was 4, max height on it right was 3, then water can trapped In this bar is min (4,3)-2 = 1.
Thus, we can scan the whole map twice to get the max height on right and left, respectively. Finally scan the map again to get the water trapped of all.
Public classSolution { Public intTrapint[] A) {if(A.length = = 0 | | A.length = = 1)return0; int[] L =New int[A.length]; int[] r =New int[A.length]; l[0] = 0; for(inti = 1; i < a.length; i++) {L[i]= Math.max (A[i-1], l[i-1]); } r[a.length-1] = 0; for(inti = a.length-2; I >= 0; i--) {R[i]= Math.max (a[i+1], r[i+1]); } intsum = 0; for(inti = 0;i < a.length;i++) { if(Math.min (L[i],r[i])-a[i] >0) {sum+ = Math.min (L[i],r[i])-A[i]; } } returnsum; }}
Trapping Rain Water