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!
First, analyze each a[i] can trapped water capacity, and then add all the trapped water capacity of all A[i] can be second, for each a[i] can trapped water capacity, depending on a[i] The difference between the left and right sides of the height (extendable) of the lower value and the a[i], i.e. volume[i] = [min (Left[i], right[i])-a[i]] * 1, here 1 is the width, if the width of each bar is 2, it will be multiplied by 2 "
So how do you find the right and left height of a[i]? You know, how much water can be the main look at the short board. So for each a[i], ask for a top left short plate, and then ask for a top right short plate, the two direct shortest board minus A[i] The original value is how much water can become.
So it takes two times to traverse, one from left to right, to find the highest left short plate, and one from right to left, to find the highest right short plate. The final record of the total amount of water is the end result.
PackageLeetcode2; Public classTrappingrainwater { Public Static intTrapping (int[] A) { if(a==NULL){ return0; } intMaxvol=0; intLmax=0; int[] vol=New int[A.length]; int[] left=New int[A.length]; int[] right=New int[A.length]; for(inti=0;i<a.length;i++) {Left[i]=Math.max (Lmax, a[i]); Lmax=Math.max (Lmax,a[i]); } intRmax=0; for(inti=a.length-1;i>0;i--) {Right[i]=Math.max (Rmax,a[i]); Rmax=Math.max (Rmax, a[i]); } for(inti=0;i<a.length;i++) {Vol[i]=1* (Math.min (Left[i], right[i])-A[i]); if(vol[i]>0) {Maxvol=maxvol+Vol[i]; } } returnMaxvol; } Public Static voidMain (string[] args) {//TODO auto-generated Method Stub int[] a={0,1,0,2,1,0,1,3,2,1,2,1}; System.out.println (Trapping (a)); }}
Trapping Rain Water