forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
trapping-rain-water.cpp
35 lines (31 loc) · 931 Bytes
/
trapping-rain-water.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
// Time: O(n)
// Space: O(1)
class Solution {
public:
int trap(vector<int>& height) {
if (height.empty()) {
return 0;
}
int i = 0, j = height.size() - 1;
int left_height = height[0];
int right_height = height[height.size() - 1];
int trap = 0;
while (i < j) {
if (left_height < right_height) {
++i;
// Fill in the gap.
trap += max(0, left_height - height[i]);
// Update current max height from left.
left_height = max(left_height, height[i]);
}
else {
--j;
// Fill in the gap.
trap += max(0, right_height - height[j]);
// Update current max height from right.
right_height = max(right_height, height[j]);
}
}
return trap;
}
};