-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trapping Rain Water.cpp
73 lines (56 loc) · 1.43 KB
/
Trapping Rain Water.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
61
62
63
64
65
66
67
68
69
70
71
72
73
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
// Function to find the trapped water between the blocks.
public:
long long trappingWater(int arr[], int n){
// code here
int a=0,b=1,a_;
long long sum =0;
while(a!=b-1 || b<n){
if( b == n && a!=b-1){
for(int i=0;i<b-a;i++){
sum -= arr[a] - arr[i+a];
}
a_ = a;
a = b-1;
b = b-2;
while(b>a_){
if( arr[a] > arr[b] )
sum += arr[a] - arr[b];
else
a=b;
b--;
}
break;
}
if( arr[a] > arr[b] )
sum += arr[a] - arr[b];
else
a=b;
b++;
}
return sum;
}
};
//{ Driver Code Starts.
int main(){
int t;
//testcases
cin >> t;
while(t--){
int n;
//size of array
cin >> n;
int a[n];
//adding elements to the array
for(int i =0;i<n;i++){
cin >> a[i];
}
Solution obj;
//calling trappingWater() function
cout << obj.trappingWater(a, n) << endl;
}
return 0;
}