-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trapping rain water
54 lines (50 loc) · 1.07 KB
/
Trapping rain water
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
class Solution {
public:
int trap(vector<int>& arr) {
int n = arr.size() ;
vector <int> leftmax(n , 0) ;
vector <int> rightmax(n , 0) ;
for(int i = 0 ; i < n ; i++)
{
if(i == 0)
{
leftmax[i] = arr[i] ;
continue ;
}
if(arr[i] >= leftmax[i - 1])
{
leftmax[i] = arr[i] ;
}
else
{
leftmax[i] = leftmax[i - 1];
}
}
for(int i = n - 1 ; i >= 0 ; i--)
{
if(i == n - 1)
{
rightmax[i] = arr[i] ;
continue ;
}
if(arr[i] >= rightmax[i + 1])
{
rightmax[i] = arr[i] ;
}
else
{
rightmax[i] = rightmax[i + 1];
}
}
for(int i = 0 ; i < n ; i++)
{
// cout << leftmax[i] << rightmax[i] << endl ;
}
int c = 0 ;
for(int i = 0 ; i < n ; i++)
{
c = c + min(leftmax[i],rightmax[i]) - arr[i] ;
}
return c ;
}
};