-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathRainWaterTrapped.cpp
88 lines (61 loc) · 1.87 KB
/
RainWaterTrapped.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
79
80
81
82
83
84
85
/*
https://www.interviewbit.com/problems/rain-water-trapped/
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
Example :
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
*/
# 1st method (using Stack)
int Solution::trap(const vector<int> &A)
{
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
stack<int> st;
int vol = 0;
for(auto i=0; i<A.size(); i++)
{
while(!st.empty() && A[i] > A[st.top()])
{
int j = st.top();
st.pop();
if(st.empty())
break;
int d = i - st.top() - 1;
int bounded_height = min(A[i], A[st.top()]) - A[j];
vol += d*bounded_height;
}
st.push(i);
}
return vol;
}
# 2nd method (two pointer)
int Solution::trap(const vector<int> &A)
{
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
int l = 0, r = A.size()-1;
int vol = 0, l_max = 0, r_max = 0;
while(l < r)
{
if(A[l] < A[r])
{
if(A[l] >= l_max)
l_max = A[l];
else
vol += (l_max - A[l]);
++l;
}
else
{
if(A[r] >= r_max)
r_max = A[r];
else
vol += (r_max - A[r]);
--r;
}
}
return vol;
}