-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathtrappingRainwater.cpp
78 lines (62 loc) · 1.54 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* C++ program to solve Trapping Rainwater problem.An array of non-negative integers are given which
represent an elevation height each of width 1, the
goal is to compute total water trapped after raining*/
#include<bits/stdc++.h>
using namespace std;
class Trapwater {
public:
int trap(vector<int>& height){
int n = height.size();
int left = 0 , right = n-1;
// Initialize output
int res = 0;
// Maximum element on left and right
int max_left = 0, max_right = 0;
while(left <= right){
if(height[left] <= height[right]){
if(height[left] >= max_left)
// Update max in left
max_left = height[left];
else
// Water trapped on current index is max - current height
res += max_left - height[left];
left++;
}
else{
if(height[right] >= max_right)
// Update max in right
max_right = height[right];
else
res += max_right - height[right];
right--;
}
return res;
}
};
int main(){
int n,h;
vector<int> height;
// Taking input of number of buildings
cin >> n;
while(n--){
// input the height of each building
cin >> val;
height.push_back(h);
}
Trapwater t;
int result = t.trap(height);
// display the amount of water trapped
cout << result;
}
/*
Input -
n = 5
arr[n] = {2,3,1,0,5}
Sample Output -
5
Explanation -
Two units of water can be stored at index 2 and
3 units at index 3
Time Complexity : O(n)
Space Complexity : O(1)
*/