Kadane’s algorithm for maxm subarray sum is okay for an array containing a mix of both +ve and -ve numbers or when there are only +ve numbers. But a test case may pop up that has all -ve numbers like {-9, -8, -6, -3, -1} or anything like that and we might be required to output -1 (basically when empty subarray is not a valid option).
For that, i have written this function. Please see and check if it can be made better.
int maxSubarraySum(int ar[], int n){
int lowestSoFar = ar[0], maxSum = INT_MIN;
for(int i = 1; i < n; i++){
ar[i]+=ar[i-1];
maxSum = max(maxSum, ar[i]-lowestSoFar);
lowestSoFar = min(lowestSoFar, ar[i]);
}
return maxSum;
}
and the same thing can be converted to Kadane’s algorithm by swapping the reassignment statements of maxSum and lowestSoFar.
