Skip to content

Commit 37925b9

Browse files
add problem 42 and test function
1 parent d20099a commit 37925b9

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

C/1-50/42-Trapping-Rain-Water.c

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
* Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
3+
4+
* For example,
5+
* Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
6+
* Created by supercoderx on 2017/8/13.
7+
*/
8+
#include
9+
10+
int trap(int *height, int heightSize) {
11+
if (heightSize < 2)
12+
return 0;
13+
int volume = 0, maxLeft, maxRight;
14+
for (int i = 0; i < heightSize; i++) {
15+
maxLeft = maxRight = height[i];
16+
for (int j = 0; j < i; j++) {
17+
if (height[j] > maxLeft)
18+
maxLeft = height[j];
19+
}
20+
for (int k = i + 1; k < heightSize; k++) {
21+
if (height[k] > maxRight)
22+
maxRight = height[k];
23+
}
24+
volume += (maxLeft < maxRight ? maxLeft : maxRight) - height[i];
25+
}
26+
return volume;
27+
}
28+
29+
void testTrap() {
30+
int a[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
31+
int b[] = {5, 2, 1, 2, 1, 5};
32+
printf("%d\n", trap(b, sizeof(b) / sizeof(b[0])));
33+
printf("%d", trap(a, sizeof(a) / sizeof(a[0])));
34+
}

0 commit comments

Comments
 (0)