#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;
for (int i = 0; i < n; i++) {
sum += arr[i];
if (sum > maxi) {
maxi = sum;
}
// If sum < 0: discard the sum calculated
if (sum < 0) {
sum = 0;
}
}
// 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+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgpsb25nIGxvbmcgbWF4U3ViYXJyYXlTdW0oaW50IGFycltdLCBpbnQgbikgewogICAgbG9uZyBsb25nIG1heGkgPSBMT05HX01JTjsgLy8gbWF4aW11bSBzdW0KICAgIGxvbmcgbG9uZyBzdW0gPSAwOwoKICAgIGZvciAoaW50IGkgPSAwOyBpIDwgbjsgaSsrKSB7CgogICAgICAgIHN1bSArPSBhcnJbaV07CgogICAgICAgIGlmIChzdW0gPiBtYXhpKSB7CiAgICAgICAgICAgIG1heGkgPSBzdW07CiAgICAgICAgfQoKICAgICAgICAvLyBJZiBzdW0gPCAwOiBkaXNjYXJkIHRoZSBzdW0gY2FsY3VsYXRlZAogICAgICAgIGlmIChzdW0gPCAwKSB7CiAgICAgICAgICAgIHN1bSA9IDA7CiAgICAgICAgfQogICAgfQoKICAgIC8vIFRvIGNvbnNpZGVyIHRoZSBzdW0gb2YgdGhlIGVtcHR5IHN1YmFycmF5CiAgICAvLyB1bmNvbW1lbnQgdGhlIGZvbGxvd2luZyBjaGVjazoKCiAgICAvL2lmIChtYXhpIDwgMCkgbWF4aSA9IDA7CgogICAgcmV0dXJuIG1heGk7Cn0KCmludCBtYWluKCkKewogICAgaW50IGFycltdID0geyAtMiwgMSwgLTMsIDQsIC0xLCAyLCAxLCAtNSwgNH07CiAgICBpbnQgbiA9IHNpemVvZihhcnIpIC8gc2l6ZW9mKGFyclswXSk7CiAgICBsb25nIGxvbmcgbWF4U3VtID0gbWF4U3ViYXJyYXlTdW0oYXJyLCBuKTsKICAgIGNvdXQgPDwgIlRoZSBtYXhpbXVtIHN1YmFycmF5IHN1bSBpczogIiA8PCBtYXhTdW0gPDwgZW5kbDsKICAgIHJldHVybiAwOwp9Cg==