-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathtrapping rainwater.cpp
More file actions
27 lines (26 loc) · 921 Bytes
/
trapping rainwater.cpp
File metadata and controls
27 lines (26 loc) · 921 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
27
/*
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
*/
class Solution { // 0 ms, faster than 100.00%
public int trap(int[] height) {
if (height.length <= 2) return 0;
int n = height.length, maxLeft = height[0], maxRight = height[n-1];
int left = 1, right = n - 2, ans = 0;
while (left <= right) {
if (maxLeft < maxRight) {
if (height[left] > maxLeft)
maxLeft = height[left];
else
ans += maxLeft - height[left];
left += 1;
} else {
if (height[right] > maxRight)
maxRight = height[right];
else
ans += maxRight - height[right];
right -= 1;
}
}
return ans;
}
}