-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtrapping_rain_water_problem.cpp
More file actions
46 lines (45 loc) · 980 Bytes
/
trapping_rain_water_problem.cpp
File metadata and controls
46 lines (45 loc) · 980 Bytes
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
// trapping rain water problem
//https://leetcode.com/problems/trapping-rain-water/
class Solution {
public:
int trap(vector<int>& a)
{
int n=a.size();
if(n==0)
return 0;
int j,i,k=0;
int water=0;
for(i=0;i<n;i++)
{
if(a[k]<a[i])
{
k=i; // find index of max height bar
}
}
j=0;
for(i=1;i<k;i++)
{
if(a[i]<a[j])
{
water+=a[j]-a[i]; // water stored on left of k
}
else
{
j=i;
}
}
j=n-1;
for(i=n-2;i>k;i--)
{
if(a[i]<a[j])
{
water+=a[j]-a[i]; // water stored on right of k
}
else
{
j=i;
}
}
return water;
}
};