Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
1 class Solution { 2 public: 3 int trap(vector<int>& height) { 4 int max=0; 5 for(int i=0;i<height.size();i++) 6 { 7 if(height[i]>height[max]) 8 max=i; 9 } 10 11 int water=0; 12 13 for(int i=0,peak=0;i<max;i++) 14 if(height[i]>peak) 15 peak=height[i]; 16 else 17 water=water+peak-height[i]; 18 19 for(int i=height.size()-1,top=0;i>max;i--) 20 if(height[i]>top) 21 top=height[i]; 22 else 23 water=water+top-height[i]; 24 25 return water; 26 } 27 };