42. Trapping Rain Water
C++:
1 class Solution { 2 public: 3 int trap(vector<int>& height) { 4 int left = 0 ; 5 int right = height.size() - 1; 6 int res = 0 ; 7 int maxLeft = 0 , maxRight = 0 ; 8 while(left <= right){ 9 if (height[left] <= height[right]){ 10 if (height[left] >= maxLeft){ 11 maxLeft = height[left] ; 12 }else{ 13 res += maxLeft - height[left] ; 14 } 15 left++ ; 16 }else{ 17 if (height[right] >= maxRight){ 18 maxRight = height[right] ; 19 }else{ 20 res += maxRight - height[right] ; 21 } 22 right-- ; 23 } 24 } 25 return res ; 26 } 27 };