fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. long long maxSubarraySum(int arr[], int n) {
  5. long long maxi = LONG_MIN; // maximum sum
  6. long long sum = 0;
  7.  
  8. int start = 0;
  9. int ansStart = -1, ansEnd = -1;
  10. for (int i = 0; i < n; i++) {
  11.  
  12. if (sum == 0) start = i; // starting index
  13.  
  14. sum += arr[i];
  15.  
  16. if (sum > maxi) {
  17. maxi = sum;
  18.  
  19. ansStart = start;
  20. ansEnd = i;
  21. }
  22.  
  23. // If sum < 0: discard the sum calculated
  24. if (sum < 0) {
  25. sum = 0;
  26. }
  27. }
  28.  
  29. //printing the subarray:
  30. cout << "The subarray is: [";
  31. for (int i = ansStart; i <= ansEnd; i++) {
  32. cout << arr[i] << " ";
  33. }
  34. cout << "]n";
  35.  
  36. // To consider the sum of the empty subarray
  37. // uncomment the following check:
  38.  
  39. //if (maxi < 0) maxi = 0;
  40.  
  41. return maxi;
  42. }
  43.  
  44. int main()
  45. {
  46. int arr[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4};
  47. int n = sizeof(arr) / sizeof(arr[0]);
  48. long long maxSum = maxSubarraySum(arr, n);
  49. cout << "The maximum subarray sum is: " << maxSum << endl;
  50. return 0;
  51. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
The subarray is: [4 -1 2 1 ]nThe maximum subarray sum is: 6