Guest User

Untitled

a guest
Sep 11th, 2012
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. // see http://stackoverflow.com/a/7943955/7507
  4.  
  5. int main(int argc, char *argv[]) {
  6.  
  7. int bestSoFar = 0;
  8. int bestNow = 0;
  9. int bestStartIndexSoFar = -1;
  10. int bestStopIndexSoFar = -1;
  11. int bestStartIndexNow = -1;
  12.  
  13. int array[] = {3, -1, 5, -6, -9};
  14. int array_len = sizeof(array)/sizeof(int);
  15.  
  16. for(int i = 0; i < array_len; i++) {
  17. int value = bestNow + array[i];
  18.  
  19. if(value > 0) {
  20. if (bestNow == 0) {
  21. bestStartIndexNow = i;
  22. }
  23. bestNow = value;
  24. } else {
  25. bestNow = 0;
  26. }
  27.  
  28. if(bestNow > bestSoFar) {
  29. bestSoFar = bestNow;
  30. bestStopIndexSoFar = i;
  31. bestStartIndexSoFar = bestStartIndexNow;
  32. }
  33. }
  34.  
  35. printf("Best Sum = %d\n", bestSoFar);
  36. printf("Max Array = [");
  37.  
  38. for(int i = bestStartIndexSoFar; i < bestStopIndexSoFar + 1; i++) {
  39. printf(" %d", array[i]);
  40. }
  41.  
  42. printf(" ]\n");
  43.  
  44. }
Advertisement
Add Comment
Please, Sign In to add comment