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!
[Ideas for solving problems]
For any one coordinate, check its left and right maximum coordinates, then subtract is the volume. So
1. Scan from left to right, for each coordinate, find the maximum value on the left.
2. Scan from right to left, for each coordinate, find the maximum right value.
3. Scan again for volume and add.
#2和 # # can be combined into a loop,
1 classSolution {2 Public:3 intTrapintA[],intN) {4 if(n<3)return 0;5 intres=0;6vector<int> MaxL (N,0);7 intmaxtemp=a[0];8maxl[0]=maxtemp;9 for(intI=1; i<n;i++)Ten { Onemaxl[i]=maxtemp; A if(a[i]>maxtemp) -maxtemp=A[i]; - } thevector<int> MaxR (N,0); -maxtemp=a[n-1]; -maxr[n-1]=maxtemp; - for(inti=n-2; i>=0; i--) + { -maxr[i]=maxtemp; + intVol=min (Maxr[i],maxl[i])-A[i]; A if(vol>0) res+=Vol; at if(a[i]>maxtemp) -maxtemp=A[i]; - } - returnRes; - } -};
Only one array is allowed.
1 classSolution {2 Public:3 intTrapintA[],intN) {4 if(n<3)return 0;5 intres=0;6vector<int> MaxL (N,0);7 intmaxtemp=a[0];8maxl[0]=maxtemp;9 for(intI=1; i<n;i++)Ten { Onemaxl[i]=maxtemp; A if(a[i]>maxtemp) -maxtemp=A[i]; - } the -maxtemp=a[n-1]; - - for(inti=n-2; i>=0; i--) + { - intVol=min (Maxtemp,maxl[i])-A[i]; + if(vol>0) res+=Vol; A if(a[i]>maxtemp) atmaxtemp=A[i]; - } - returnRes; - } -};