Skip to content

Commit

Permalink
Trap water
Browse files Browse the repository at this point in the history
Signed-off-by: Leo Ma <[email protected]>
  • Loading branch information
begeekmyfriend committed Jul 30, 2017
1 parent 8d7c8b0 commit 4289e3f
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 042_trapping_rain_water/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test trap_water.c
57 changes: 57 additions & 0 deletions 042_trapping_rain_water/trap_water.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#include <stdio.h>
#include <stdlib.h>

static int trap(int* height, int heightSize) {
if (heightSize < 2) {
return 0;
}

int i, j, top0 = -1, top1 = -1, sum = 0, level = 0;
for (i = 0; i < heightSize; i++) {
if (height[i] > 0) {
top0 = i;
break;
}
}

while (i < heightSize) {
top1 = -1;
for (j = i + 1; j < heightSize; j++) {
if (height[j] >= height[j - 1]) {
if (top1 < 0 || height[j] >= height[top1]) {
top1 = j;
}
if (height[j] >= height[top0]) {
break;
}
}
}

if (top1 >= 0) {
int level = height[top0] < height[top1] ? height[top0] : height[top1];
while (i < top1) {
if (level > height[i]) {
sum += level - height[i];
}
i++;
}
top0 = top1;
i = top1;
} else {
i = j;
}
}

return sum;
}

int main(int argc, char **argv)
{
int i, count = argc - 1;
int *nums = malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
nums[i] = atoi(argv[i + 1]);
}
printf("%d\n", trap(nums, count));
return 0;
}

0 comments on commit 4289e3f

Please sign in to comment.