-
Notifications
You must be signed in to change notification settings - Fork 253
/
TrapRainwater.cpp
63 lines (55 loc) · 1.07 KB
/
TrapRainwater.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
#include <bits/stdc++.h>
#include <vector>
using namespace std;
int trapwater(vector<int> &height)
{
int n=height.size();
if(n<=2)
{
return 0;
}
int maxleft=height[0];
int maxright=height[n-1];
int left=1;
int right=n-2;
int trapwater=0;
while(left<=right)
{
if(maxleft<=maxright)
{
if(height[left]>=maxleft)
{
maxleft=height[left];
}
else
{
trapwater+=maxleft-height[left];
}
left++;
}
else
{
if(height[right]>=maxright)
{
maxright=height[right];
}
else
{
trapwater+=maxright-height[right];
}
right--;
}
}
return trapwater;
}
int main()
{
vector<int> height;
height.push_back(4);
height.push_back(2);
height.push_back(0);
height.push_back(3);
height.push_back(2);
height.push_back(5);
cout<<trapwater(height);
}