long long maxSubarraySum(int arr[], int n){
long long maxSum = INT_MIN;
for(int size = 1; size <= n; size++) // loop for size from 1 to n
for(int start = 0; start <= n - size; start++) { // start from 0 to totalSize - CurrentSize
long long sum = 0;
for(int i = start; i < size + start; i++)
sum += arr[i];
maxSum = max(maxSum, sum);
}
return maxSum;
}
Complexity
Time Complexity: O(n3)
Space Complexity: O(1)
Using Kaden's Algorithm
Logic
Calculate the running sum
Update max sum with the running sum
If the running sum is purely negative
the next element is the running sum
else add the next element to the running sum
Code
long long maxSubarraySum(int arr[], int n){
int sum = 0;
int maxSum = INT_MIN;
for(int i = 0; i < n; i++) {
if(sum < 0)
sum = arr[i];
else
sum += arr[i];
maxSum = max(maxSum, sum);
}
return maxSum;
}