#include <bits/stdc++.h>
using namespace std;
long long maxSubarraySum(int arr[], int n) {
long long maxi = LONG_MIN; // maximum sum
long long sum = 0;
int start = 0;
int ansStart = -1, ansEnd = -1;
for (int i = 0; i < n; i++) {
if (sum == 0) start = i; // starting index
sum += arr[i];
if (sum > maxi) {
maxi = sum;
ansStart = start;
ansEnd = i;
}
// If sum < 0: discard the sum calculated
if (sum < 0) {
sum = 0;
}
}
//printing the subarray:
cout << "The subarray is: [";
for (int i = ansStart; i <= ansEnd; i++) {
cout << arr[i] << " ";
}
cout << "]n";
// To consider the sum of the empty subarray
// uncomment the following check:
//if (maxi < 0) maxi = 0;
return maxi;
}
int main()
{
int arr[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4};
int n = sizeof(arr) / sizeof(arr[0]);
long long maxSum = maxSubarraySum(arr, n);
cout << "The maximum subarray sum is: " << maxSum << endl;
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgpsb25nIGxvbmcgbWF4U3ViYXJyYXlTdW0oaW50IGFycltdLCBpbnQgbikgewogICAgbG9uZyBsb25nIG1heGkgPSBMT05HX01JTjsgLy8gbWF4aW11bSBzdW0KICAgIGxvbmcgbG9uZyBzdW0gPSAwOwoKICAgIGludCBzdGFydCA9IDA7CiAgICBpbnQgYW5zU3RhcnQgPSAtMSwgYW5zRW5kID0gLTE7CiAgICBmb3IgKGludCBpID0gMDsgaSA8IG47IGkrKykgewoKICAgICAgICBpZiAoc3VtID09IDApIHN0YXJ0ID0gaTsgLy8gc3RhcnRpbmcgaW5kZXgKCiAgICAgICAgc3VtICs9IGFycltpXTsKCiAgICAgICAgaWYgKHN1bSA+IG1heGkpIHsKICAgICAgICAgICAgbWF4aSA9IHN1bTsKCiAgICAgICAgICAgIGFuc1N0YXJ0ID0gc3RhcnQ7CiAgICAgICAgICAgIGFuc0VuZCA9IGk7CiAgICAgICAgfQoKICAgICAgICAvLyBJZiBzdW0gPCA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