-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path42. Trapping Rain Water
34 lines (31 loc) · 1.01 KB
/
42. 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
class Solution {
public:
int trap(vector<int>& height) {
int n=height.size();
vector<int>lm(n); // to store left max value
vector<int>rm(n); // to store right max value
int max=height[0]; // because first element will always max in right left side
lm[0]=max;
// assigning the max value in the lm
for(int i=1; i<n; i++){
if(max<height[i])
max=height[i];
lm[i]=max;
}
max=height[n-1]; // because last element will always max in left side
rm[n-1]=max;
int total=0;
// assigning the max value in the rm
for(int i=n-2; i>=0; i--){
if(max<height[i])
max=height[i];
rm[i]=max;
}
for(int i=1; i<n-1; i++)
{
if((lm[i-1] > height[i])&& (rm[i+1]>height[i]))
total+=min((lm[i-1]-height[i]),(rm[i+1]- height[i])); //because at that index total water will be this
}
return total;
}
};