Skip to content

Commit 573ddbd

Browse files
authored
Created Trapping_Rain_Water.cpp using c++
C++ program to find maximum amount of water that can be trapped within given set of bars.
1 parent dbb1540 commit 573ddbd

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Trapping_rain_Water.cpp

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// This code is contributed by Avinash Prasad (GitHub : avinash11a)
2+
// C++ program to find maximum amount of water that can
3+
// be trapped within given set of bars.
4+
// Space Complexity : O(1)
5+
6+
#include<iostream>
7+
using namespace std;
8+
9+
int findWater(int arr[], int n)
10+
{
11+
// initialize output
12+
int result = 0;
13+
14+
// maximum element on left and right
15+
int left_max = 0, right_max = 0;
16+
17+
// indices to traverse the array
18+
int lo = 0, hi = n-1;
19+
20+
while(lo <= hi)
21+
{
22+
if(arr[lo] < arr[hi])
23+
{
24+
if(arr[lo] > left_max)
25+
// update max in left
26+
left_max = arr[lo];
27+
else
28+
// water on curr element = max - curr
29+
result += left_max - arr[lo];
30+
lo++;
31+
}
32+
else
33+
{
34+
if(arr[hi] > right_max)
35+
// update right maximum
36+
right_max = arr[hi];
37+
else
38+
result += right_max - arr[hi];
39+
hi--;
40+
}
41+
}
42+
43+
return result;
44+
}
45+
46+
int main()
47+
{
48+
int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
49+
int n = sizeof(arr)/sizeof(arr[0]);
50+
cout << "Maximum water that can be accumulated is "
51+
<< findWater(arr, n);
52+
}
53+
54+
// This code is contributed by Avinash Prasad

0 commit comments

Comments
 (0)