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. for (int i = 0; i < n; i++) {
  9.  
  10. sum += arr[i];
  11.  
  12. if (sum > maxi) {
  13. maxi = sum;
  14. }
  15.  
  16. // If sum < 0: discard the sum calculated
  17. if (sum < 0) {
  18. sum = 0;
  19. }
  20. }
  21.  
  22. // To consider the sum of the empty subarray
  23. // uncomment the following check:
  24.  
  25. //if (maxi < 0) maxi = 0;
  26.  
  27. return maxi;
  28. }
  29.  
  30. int main()
  31. {
  32. int arr[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4};
  33. int n = sizeof(arr) / sizeof(arr[0]);
  34. long long maxSum = maxSubarraySum(arr, n);
  35. cout << "The maximum subarray sum is: " << maxSum << endl;
  36. return 0;
  37. }
  38.  
Success #stdin #stdout 0s 5268KB
stdin
Standard input is empty
stdout
The maximum subarray sum is: 6