forked from aayushi1499/Hacktoberfest2021-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trapping_rain_water_dp.cpp
70 lines (51 loc) · 1.31 KB
/
Trapping_rain_water_dp.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
#include<bits/stdc++.h>
using namespace std;
class Solution{
// Function to find the trapped water between the blocks.
public:
int trappingWater(int arr[], int n){
// Code here
int l=0;
int r=n-1;
int leftmax=0;
int rightmax=0;
int res=0;
while(l<=r){
if(arr[l]<=arr[r]){
if(arr[l]>=leftmax){
leftmax=arr[l];
}else{
res+=leftmax-arr[l];
}
l++;
}else{
if(arr[r]>=rightmax){
rightmax=arr[r];
}else{
res+=rightmax-arr[r];
}
r--;
}
}
return res;
}
};
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;
} \