-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
39 lines (39 loc) · 978 Bytes
/
Solution.cs
File metadata and controls
39 lines (39 loc) · 978 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
28
29
30
31
32
33
34
35
36
37
38
39
public class Solution
{
public int Trap(int[] height)
{
int n = height.Length;
int ans = 0;
int left = 0, right = n - 1;
int maxLeft = 0, maxRight = 0;
// ans[i] = max(min(maxLeft[i], maxRight[i])-height[i], 0);
while (left <= right)
{
if (height[left] <= height[right])
{
if (height[left] >= maxLeft)
{
maxLeft = height[left];
}
else
{
ans += maxLeft - height[left];
}
left++;
}
else
{
if (height[right] >= maxRight)
{
maxRight = height[right];
}
else
{
ans += maxRight - height[right];
}
right--;
}
}
return ans;
}
}