forked from gitHub1akash/java_tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrappingRainWater.cpp
More file actions
26 lines (26 loc) · 791 Bytes
/
TrappingRainWater.cpp
File metadata and controls
26 lines (26 loc) · 791 Bytes
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
class Solution {
public:
int trap(vector<int>& h) {
// edge case: empty input
if (!h.size()) return 0;
// support variables
int i = 0, j = h.size() - 1, maxLeft = h[i], maxRight = h[j], res = 0, e;
while (i <= j) {
// case 1: i points to a bigger element, so we advance j
if (h[i] > h[j]) {
e = h[j];
if (e > maxRight) maxRight = e;
else res += maxRight - e;
j--;
}
// case 2: j points to a bigger/equal element, so we advance i
else {
e = h[i];
if (e > maxLeft) maxLeft = e;
else res += maxLeft - e;
i++;
}
}
return res;
}
};