diff --git a/Interview Questions/Trapping Rain Water/README.md b/Interview Questions/Trapping Rain Water/README.md new file mode 100644 index 00000000..7af8f70d --- /dev/null +++ b/Interview Questions/Trapping Rain Water/README.md @@ -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. \ No newline at end of file diff --git a/Interview Questions/Trapping Rain Water/Trapping Rain Water.cpp b/Interview Questions/Trapping Rain Water/Trapping Rain Water.cpp new file mode 100644 index 00000000..9376a0f8 --- /dev/null +++ b/Interview Questions/Trapping Rain Water/Trapping Rain Water.cpp @@ -0,0 +1,63 @@ +// C++ implementation of the approach +#include +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; +} + +