-
-
Notifications
You must be signed in to change notification settings - Fork 88
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #337 from sameer2403/master
Added one interview question on trapping rain water
- Loading branch information
Showing
2 changed files
with
75 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
63
Interview Questions/Trapping Rain Water/Trapping Rain Water.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
|
||
|