diff --git a/Solutions/42TrappingRainWater.cpp b/Solutions/42TrappingRainWater.cpp new file mode 100644 index 0000000..7dc41d5 --- /dev/null +++ b/Solutions/42TrappingRainWater.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int trap(vector& height) { + int n = height.size(); + int lmax = height[0]; + int rmax = height[n-1]; + int lpos = 1; + int rpos = n-2; + int water = 0; + while(lpos <= rpos) + { + if(height[lpos] >= lmax) + { + lmax = height[lpos]; + lpos++; + } + else if(height[rpos] >= rmax) + { + rmax = height[rpos]; + rpos--; + } + else if(lmax <= rmax && height[lpos] < lmax) + { + water += lmax - height[lpos]; + lpos++; + } + else + { + water += rmax - height[rpos]; + rpos--; + } + + } + return water; + } +};