From ab966842a1a899d5cbbc60508862ce0e7515f5d6 Mon Sep 17 00:00:00 2001 From: Ninad2003 <138314895+Ninad2003@users.noreply.github.com> Date: Mon, 9 Oct 2023 11:35:53 +0530 Subject: [PATCH] Create 42TrappingRainWater.cpp --- Solutions/42TrappingRainWater.cpp | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Solutions/42TrappingRainWater.cpp 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; + } +};