From eb96152654ed52de359309f434a716643b3892f8 Mon Sep 17 00:00:00 2001 From: StealthX2k20 <61972131+StealthX2k20@users.noreply.github.com> Date: Sun, 28 Feb 2021 11:46:17 +0530 Subject: [PATCH] Solution to rain water trapping problem leetcode --- Interview/Trapping Rain Water.cpp | 44 +++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Interview/Trapping Rain Water.cpp diff --git a/Interview/Trapping Rain Water.cpp b/Interview/Trapping Rain Water.cpp new file mode 100644 index 0000000..ca20888 --- /dev/null +++ b/Interview/Trapping Rain Water.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + int trap(vector& height) { + int prevMaxHeight, result = 0, curResult = 0, peakIndex; + + prevMaxHeight = 0; + + for(int i = 1; i < height.size(); i++) + { + if(height[i] < height[prevMaxHeight]) + { + curResult += (height[prevMaxHeight] - height[i]); + } + + else + { + result += curResult; + curResult = 0; + prevMaxHeight = i; + } + } + + peakIndex = prevMaxHeight; + prevMaxHeight = height.size() - 1; + curResult = 0; + + for(int i = height.size() - 2; i >= peakIndex; i--) + { + if(height[i] < height[prevMaxHeight]) + { + curResult += (height[prevMaxHeight] - height[i]); + } + + else + { + result += curResult; + curResult = 0; + prevMaxHeight = i; + } + } + + return result; + } +};