Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
added 42 Trapping Rain Water C++
  • Loading branch information
prashansatanwar committed Oct 3, 2021
commit 70ea77c130864eac7255298519d1fd1c38374c9b
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"files.associations": {
"vector": "cpp"
}
}
35 changes: 35 additions & 0 deletions C++/trapping-rain-water.cpp
Original file line number Diff line number Diff line change
@@ -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<int>& height) {
int n = height.size();

if(n==0) return 0;

vector<int> prefix(n);
vector<int> suffix(n);

prefix[0] = height[0];
for(int i = 1; i<n; i++){
prefix[i] = max(prefix[i-1],height[i]);
}

suffix[n-1] = height[n-1];
for(int i = n-2; i>=0; i--){
suffix[i] = max(suffix[i+1],height[i]);
}

int ans = 0;
for(int i = 0; i<n; i++){
int x = min(prefix[i],suffix[i])-height[i];
if(x>0) ans+=x;
}

return ans;
}
};
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | |

<br/>
<div align="right">
Expand Down