Created
October 19, 2014 18:51
-
-
Save jimexist/43b703b67e2699e3ad3d to your computer and use it in GitHub Desktop.
rain container
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <assert.h> | |
| #define max(A, B) ((A) > (B) ? (A) : (B)) | |
| #define min(A, B) ((A) < (B) ? (A) : (B)) | |
| int contained(int *cont, size_t len) { | |
| if (len == 0) { | |
| return 0; | |
| } | |
| int *left = (int *) malloc(sizeof(int) * len); | |
| assert(left); | |
| left[0] = cont[0]; | |
| for (int i=1; i<len; ++i) { | |
| left[i] = max(left[i-1], cont[i]); | |
| } | |
| int *right = (int *) malloc(sizeof(int) * len); | |
| assert(right); | |
| right[len-1] = cont[len-1]; | |
| for (int i=len-2; i>=0; --i) { | |
| right[i] = max(right[i+1], cont[i]); | |
| } | |
| int sum = 0; | |
| for (int i=0; i<len; ++i) { | |
| int h = min(left[i], right[i]); | |
| if (h > cont[i]) { | |
| sum += h - cont[i]; | |
| } | |
| } | |
| free(left); | |
| free(right); | |
| return sum; | |
| } | |
| int main(int argc, char *argv[]) { | |
| const int len = argc - 1; | |
| int *container = (int *) malloc(sizeof(int) * len); | |
| assert(container); | |
| for (int i=0; i<len; ++i) { | |
| container[i] = atoi(argv[i+1]); | |
| } | |
| printf("%d\n", contained(container, len)); | |
| free(container); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment