From 136e5a4f0228a8a31589052722df2bf5b6495972 Mon Sep 17 00:00:00 2001 From: Avimathu <40541476+Avimathu@users.noreply.github.com> Date: Fri, 21 Oct 2022 11:42:30 +0530 Subject: [PATCH] Trapping Rain Water (in C++) Please add this new file for the issue that I have raised for issue #1055 --- Trapping Rain Water | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Trapping Rain Water diff --git a/Trapping Rain Water b/Trapping Rain Water new file mode 100644 index 00000000..47d09392 --- /dev/null +++ b/Trapping Rain Water @@ -0,0 +1,40 @@ +#include +#include +#include +#include +using namespace std; + +int trap(vector& heights) { + if(heights.size()<=2){ + return 0; + } + vector leftToRight; + int maxHeight = heights[0]; + for(int i = 0; i < heights.size(); i++){ + maxHeight = max(maxHeight , heights[i]); + leftToRight.push_back(maxHeight - heights[i]); + } + vector rightToLeft; + maxHeight = heights[heights.size() - 1]; + for(int i = heights.size() - 1; i >= 0; i--){ + maxHeight = max(maxHeight , heights[i]); + rightToLeft.push_back(maxHeight - heights[i]); + } + reverse(rightToLeft.begin() , rightToLeft.end()); + int ans = 0; + for(int i = 0; i < heights.size(); i++){ + ans += min(leftToRight[i] , rightToLeft[i]); + } + return ans; +} +int main(){ + int n; + cin>>n; + vector heights(n,0); + for(int i=0;i>heights[i]; + } + int waterTrapped=trap(heights); + cout<