Skip to content

Commit f8ac63f

Browse files
committed
42. Trapping Rain Water
1 parent fd270db commit f8ac63f

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public int trap(int[] height) {
3+
int left = 0, right = height.length - 1;
4+
int leftmax = 0, rightmax = 0;
5+
int ans = 0;
6+
while(left < right){
7+
if(height[left] < height[right]){
8+
if(height[left] >= leftmax)
9+
leftmax = height[left];
10+
else ans += leftmax - height[left];
11+
left++;
12+
}else{
13+
if(height[right] >= rightmax)
14+
rightmax = height[right];
15+
else ans += rightmax - height[right];
16+
right--;
17+
}
18+
}
19+
return ans;
20+
}
21+
}

0 commit comments

Comments
 (0)