fork download
  1. #include <climits>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. void maxSubArraySum(int a[], int size)
  6. {
  7. int max_so_far = INT_MIN, max_ending_here = 0,
  8. start = 0, end = 0, s = 0;
  9.  
  10. for (int i = 0; i < size; i++) {
  11. max_ending_here += a[i];
  12.  
  13. if (max_so_far < max_ending_here) {
  14. max_so_far = max_ending_here;
  15. start = s;
  16. end = i;
  17. }
  18.  
  19. if (max_ending_here < 0) {
  20. max_ending_here = 0;
  21. s = i + 1;
  22. }
  23. }
  24. cout << "\nMaximum sum is " << max_so_far<< endl;
  25. cout << "\nsize of subarray " << sizeof(max_so_far);
  26. cout << "\nStarting position " << start << endl
  27. << "Ending position " << end << endl;
  28. }
  29.  
  30. int main()
  31. {
  32. int a[] = { 2, -4, -5, 12, 18, 12, 15 };
  33. int n = sizeof(a) / sizeof(a[0]);
  34. maxSubArraySum(a, n);
  35. return 0;
  36. }
Success #stdin #stdout 0.01s 5512KB
stdin
Standard input is empty
stdout
Maximum  sum is 57

size of subarray 4
Starting position 3
Ending position 6