Skip to content

Commit fc2e647

Browse files
committed
42. Trapping Rain Water
1 parent 1613176 commit fc2e647

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

csharp/42-Trapping-Rain-Water.cs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
public class Solution
2+
{
3+
4+
public int Trap(int[] height)
5+
{
6+
7+
if (height is null || height.Length == 0) return 0;
8+
9+
int left = 0, right = height.Length - 1;
10+
int leftMax = height[left], rightMax = height[right];
11+
var result = 0;
12+
13+
while (left < right)
14+
{
15+
if (leftMax < rightMax)
16+
{
17+
left++;
18+
leftMax = Math.Max(leftMax, height[left]);
19+
result += leftMax - height[left];
20+
}
21+
else
22+
{
23+
right--;
24+
rightMax = Math.Max(rightMax, height[right]);
25+
result += rightMax - height[right];
26+
}
27+
}
28+
29+
return result;
30+
}
31+
}

0 commit comments

Comments
 (0)