Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added one interview question on trapping rain water #337

Merged
merged 2 commits into from
Oct 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
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
12 changes: 12 additions & 0 deletions Interview Questions/Trapping Rain Water/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Trapping Rain Water


Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

Input: arr[] = {3, 0, 2, 0, 4}
Output: 7

Explanation:
We can trap "3 units" of water between 3 and 2,
"1 unit" on top of bar 2 and "3 units" between 2
and 4.
63 changes: 63 additions & 0 deletions Interview Questions/Trapping Rain Water/Trapping Rain Water.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;

int maxWater(int arr[], int n)
{

// indices to traverse the array
int left = 0;
int right = n-1;

// To store Left max and right max
// for two pointers left and right
int l_max = 0;
int r_max = 0;

// To store the total amount
// of rain water trapped
int result = 0;
while (left <= right)
{

// We need check for minimum of left
// and right max for each element
if(r_max <= l_max)
{

// Add the difference between
// current value and right max at index r
result += max(0, r_max-arr[right]);

// Update right max
r_max = max(r_max, arr[right]);

// Update right pointer
right -= 1;
}
else
{

// Add the difference between
// current value and left max at index l
result += max(0, l_max-arr[left]);

// Update left max
l_max = max(l_max, arr[left]);

// Update left pointer
left += 1;
}
}
return result;
}

// Driver code
int main() {
int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxWater(arr, n) << endl;
return 0;
}