forked from SakshiMishra1/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trappingRainwater.cpp
60 lines (53 loc) · 1.38 KB
/
trappingRainwater.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
51
52
53
54
55
56
57
58
59
60
//Trapping rainwater problem
// Efficient solution
// Expected Time Complexity: O(N).
// Expected Auxiliary Space: O(N).
// Asked in Amazon Microsoft Google Flipkart
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t, n;
//test cases
cin >> t;
while (t--)
{
//size of array
cin >> n;
long long arr[n];
//adding elements
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
long long 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--;
}
}
cout << result;
}
return 0;
}