15 Kaden's Alorithm
Naive Approach
Code
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;
}
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
Last updated