From 2fde4f6e843522ee2fe1005e5e0ed761b51d6909 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sat, 4 Nov 2017 09:29:14 +0800 Subject: [PATCH] Water container Signed-off-by: Leo Ma --- 011_container_with_most_water/Makefile | 2 ++ 011_container_with_most_water/container.c | 33 +++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 011_container_with_most_water/Makefile create mode 100644 011_container_with_most_water/container.c diff --git a/011_container_with_most_water/Makefile b/011_container_with_most_water/Makefile new file mode 100644 index 0000000..cfc4a90 --- /dev/null +++ b/011_container_with_most_water/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test container.c diff --git a/011_container_with_most_water/container.c b/011_container_with_most_water/container.c new file mode 100644 index 0000000..2534ab3 --- /dev/null +++ b/011_container_with_most_water/container.c @@ -0,0 +1,33 @@ +#include +#include + +static int maxArea(int* height, int heightSize) +{ + int min = 0, max = heightSize - 1; + int area_max = 0; + while (min < max) { + int area = (max - min) * (height[min] < height[max] ? height[min] : height[max]); + area_max = area > area_max ? area : area_max; + if (height[min] < height[max]) { + while (++min < max && height[min] <= height[min - 1]) { + continue; + } + } else { + while (min < --max && height[max] <= height[max + 1]) { + continue; + } + } + } + return area_max; +} + +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", maxArea(nums, count)); + return 0; +}