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!
C + + Implementation code:
#include <iostream>using namespacestd;classSolution { Public: //The key is to find the rules://that is, the amount of water stored in block i = min (the highest bar height on the left of block I, the height of the highest bar on the right of Block I)-the height of the block I local bar//example, the amount of water stored in the 5th place = min (2,3)-0 = 2//2 is the highest bar on the left, the bar of the 3rd place//3 is the highest bar on its right, the bar of the 7th place,//0 for its own bar height intTrapintA[],intN) {if(n==0) return 0; intLeft[n]; intRight[n]; inti; intsum=0; left[0]=a[0]; for(i=1; i<n;i++) Left[i]=max (left[i-1],a[i]); Right[n-1]=a[n-1]; for(i=n-2; i>=0; i--) Right[i]=max (right[i+1],a[i]); for(i=1; i<n-1; i++) Sum+ = (min (left[i],right[i])-A[i]); returnsum; }};intMain () {solution S; inta[ A]={0,1,0,2,1,0,1,3,2,1,2,1}; cout<<s.trap (A, A) <<Endl;}
Reference: http://blog.csdn.net/fightforyourdream/article/details/15026089
Trapping Rain Water