-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRainwater
40 lines (35 loc) · 982 Bytes
/
Rainwater
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
class Solution {
public:
vector<int> l(vector<int>& height) {
int n = height.size();
vector<int> lm(n);
lm[0] = height[0];
for (int i = 1; i < n; ++i) {
lm[i] = max(lm[i - 1], height[i]);
}
return lm;
}
vector<int> r(vector<int>& height) {
int n = height.size();
vector<int> rm(n);
rm[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; --i) {
rm[i] = max(rm[i + 1], height[i]);
}
return rm;
}
int trap(vector<int>& height) {
int n = height.size();
if (n == 0) return 0;
vector<int> lm = l(height);
vector<int> rm = r(height);
int totalWater = 0;
for (int i = 0; i < n; ++i) {
int waterLevel = min(lm[i], rm[i]);
if (waterLevel > height[i]) {
totalWater += waterLevel - height[i];
}
}
return totalWater;
}
};