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<