diff --git a/C++/trapping-rain-water.cpp b/C++/trapping-rain-water.cpp new file mode 100644 index 00000000..47b1fed9 --- /dev/null +++ b/C++/trapping-rain-water.cpp @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/trapping-rain-water/ + +// Idea: +// We calculate the prefix and suffix max arrays +// The water trapped would be the min of the 2 arrays at a particular index minus the actual height + +class Solution { +public: + int trap(vector& height) { + int n = height.size(); + + if(n==0) return 0; + + vector prefix(n); + vector suffix(n); + + prefix[0] = height[0]; + for(int i = 1; i=0; i--){ + suffix[i] = max(suffix[i+1],height[i]); + } + + int ans = 0; + for(int i = 0; i0) ans+=x; + } + + return ans; + } +}; \ No newline at end of file diff --git a/README.md b/README.md index 36d17c18..4fa64e86 100644 --- a/README.md +++ b/README.md @@ -387,6 +387,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu | 174 | [Dungeon Game](https://leetcode.com/problems/dungeon-game/) | [C++](./C++/dungeon-game.pp) | _O(M\*N)_ | _O(M\*N)_ | Hard | Dynamic Programming | | | 070 | [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) | [Java](./Java/climbing-stairs.java) | _O(N)_ | _O(1)_ | Easy | DP | | | 730 | [Count Different Palindromic Subsequences](https://leetcode.com/problems/count-different-palindromic-subsequences/) | [C++](./C++/Count-Different-Palindromic-Subsequences.cpp) | _O(N\*N)_ | _O(N\*N)_ | Hard | DP | | +| 42 | [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | [C++](./C++/trapping-rain-water.cpp) | _O(N)_ | _O(N)_ | Hard | DP | |