-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path042-TrappingRainWater.cs
47 lines (42 loc) · 1.42 KB
/
042-TrappingRainWater.cs
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
36
37
38
39
40
41
42
43
44
45
46
47
//-----------------------------------------------------------------------------
// Runtime: 88ms
// Memory Usage: 24.7 MB
// Link: https://leetcode.com/submissions/detail/378077559/
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _042_TrappingRainWater
{
public int Trap(int[] height)
{
int n = height.Length;
if (n == 0) { return 0; }
int maxLeftHeight = height[0], maxRightHeight = height[n - 1];
int result = 0, tempResultLeft = 0, tempResultRight = 0;
for (int i = 0; i < n; i++)
{
if (maxLeftHeight > height[i])
{
tempResultLeft += maxLeftHeight - height[i];
}
else
{
maxLeftHeight = height[i];
result += tempResultLeft;
tempResultLeft = 0;
}
if (maxRightHeight > height[n - i - 1])
{
tempResultRight += maxRightHeight - height[n - i - 1];
}
else if (maxRightHeight < height[n - i - 1])
{
maxRightHeight = height[n - i - 1];
result += tempResultRight;
tempResultRight = 0;
}
}
return result;
}
}
}