-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathp042.c
37 lines (37 loc) · 768 Bytes
/
p042.c
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
int trap(int* height, const int heightSize) {
if (heightSize <= 2) return 0;
int leftmax[heightSize];
int i;
leftmax[0] = 0;
for (i = 1; i < heightSize-1; i++)
{
if (height[i-1] < leftmax[i-1])
{
leftmax[i] = leftmax[i-1];
}
else
{
leftmax[i] = height[i-1];
}
}
int rightmax = 0;
int result = 0;
for (i = heightSize-2; i > 0; i--)
{
if (height[i+1] > rightmax)
{
rightmax = height[i+1];
}
int min = leftmax[i];
if (rightmax < min)
{
min = rightmax;
}
min -= height[i];
if (min > 0)
{
result += min;
}
}
return result;
}