-
Notifications
You must be signed in to change notification settings - Fork 186
/
trapping rainwater
40 lines (32 loc) · 934 Bytes
/
trapping 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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int trap(vector<int>& height) {
if (height.empty()) return 0;
int n = height.size();
vector<int> left_max(n);
vector<int> right_max(n);
// Fill left_max
left_max[0] = height[0];
for (int i = 1; i < n; ++i) {
left_max[i] = max(left_max[i - 1], height[i]);
}
// Fill right_max
right_max[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; --i) {
right_max[i] = max(right_max[i + 1], height[i]);
}
// Calculate trapped water
int trapped_water = 0;
for (int i = 0; i < n; ++i) {
trapped_water += min(left_max[i], right_max[i]) - height[i];
}
return trapped_water;
}
int main() {
vector<int> height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
int result = trap(height);
cout << "Trapped rainwater: " << result << " units" << endl;
return 0;
}