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
.
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 rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
1 class Solution { 2 public: 3 int trap(vector<int>& height) { 4 int n=height.size(); 5 int result=0; 6 vector<int> left(n),right(n); 7 for(int i=0;i<n;i++) 8 { 9 left[i]=i?max(left[i-1],height[i]):height[i]; 10 } 11 for(int j=n-1;j>=0;j--) 12 { 13 right[j]=(n-1-j)?max(right[j+1],height[j]):height[j]; 14 } 15 for(int k=0;k<n;k++) 16 { 17 result+=min(left[k],right[k])-height[k]; 18 } 19 return result; 20 } 21 };