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