Skip to content

Commit

Permalink
Merge pull request #337 from sameer2403/master
Browse files Browse the repository at this point in the history
Added one interview question on trapping rain water
  • Loading branch information
swaaz authored Oct 16, 2021
2 parents 2b2a596 + e3c3b0b commit cbc1f7e
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
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;
}


0 comments on commit cbc1f7e

Please sign in to comment.