Created
August 7, 2012 22:14
-
-
Save JAChapmanII/3289949 to your computer and use it in GitHub Desktop.
maximum subarray problem attempt
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> | |
| // idx = p q o | |
| // arr = [ ] | |
| // { } { } | |
| // s l arr[o] | |
| // | |
| // returns array slice, sum, leftover | |
| // | |
| // if(arr[o] + l >= 0) | |
| // return arr[p:o], s + l + arr[o], 0 | |
| // else | |
| // return arr[p:q], s, l + arr[o] | |
| // | |
| // if(arr.length == 1) | |
| // return arr[0:0], arr[0], 0 | |
| // | |
| // if(s < 0 && arr[o] > s) | |
| // p = o; => | |
| // return arr[o:o], arr[o], 0 | |
| // | |
| // ... p = o condition wrong | |
| // 1, -2, 3 \ | |
| // s = 1, l = -2, arr[o] = 3 | arr[o] > s + l + arr[o] | |
| // | 0 > s + l | |
| // ..., 8 | | |
| // s = 7, l = -1, arr[o] = 8 / | |
| // | |
| // ... all negatives... | |
| // s < 0 (otherwise continue) | |
| // arr[o] > s (otherwise we don't want arr[o]) | |
| // | |
| void msa_all(int *arr, int length); | |
| void msa(int *arr, int length); | |
| int main() { | |
| msa_all((int[]){ 1, -2, 3, 4, -1, 8, 6, -3, 4 }, 9); | |
| msa_all((int[]){ -2 }, 1); | |
| msa_all((int[]){ -8, -2, -3, -4, -1, -8, -6, -3 }, 8); | |
| msa_all((int[]){ 0, 0, 0, 0, 0 }, 5); | |
| msa_all((int[]){ 1, 2, 3 }, 3); | |
| msa_all((int[]){ -10 }, 1); | |
| msa_all((int[]){ 10 }, 1); | |
| msa_all((int[]){ 10, -2, -3, -4, -11, -8, -6, -3 }, 8); | |
| msa_all((int[]){ -10, -2, -3, -4, -11, -8, -6, -3 }, 8); | |
| msa_all((int[]){ -10, -2, -3, -4, -11, -8, -6, 3 }, 8); | |
| msa_all((int[]){ 5, 0, 0, -1, 5 }, 5); | |
| return 0; | |
| } | |
| void msa_all(int *arr, int length) { | |
| for(int i = 0; i < length; ++i) { | |
| printf("%d%s ", arr[i], i != length - 1 ? "," : ""); | |
| } | |
| printf("\n"); | |
| for(int l = 1; l <= length; ++l) | |
| msa(arr, l); | |
| printf("--------------------------------\n"); | |
| } | |
| void msa(int *arr, int length) { | |
| int p = 0, q = 0, s = arr[0], l = 0; | |
| for(int o = 1; o < length; ++o) { | |
| //printf("length: %d, p: %d, q: %d, s: %d, l: %d, arr[o]: %d\n", | |
| //length, p, q, s, l, arr[o]); | |
| if(0 > s && arr[o] > s) { | |
| p = q = o, s = arr[o], l = 0; | |
| continue; | |
| } | |
| if(arr[o] + l >= 0) { | |
| q = o, s += l + arr[o], l = 0; | |
| continue; | |
| } else { | |
| l += arr[o]; | |
| continue; | |
| } | |
| } | |
| for(int i = p; i <= q; ++i) | |
| printf("%d%s ", arr[i], i != q ? "," : ""); | |
| printf("\n"); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment