If all the elements of an array are negative then I think the program will fail, because if the value of current sum is less than zero then it is updated by zero. Hereby I’m pasting the right code for Kadane’s algo:-
int maxSum=INT_MIN;
int currSum=0;
for(int i=0;i<n;i++)
{
currSum = currSum + nums[i];
if( maxSum < currSum)
maxSum = currSum;
if( currSum < 0 )
currSum = 0;
}
cout<<maxSum;
If all the array elements are negative then the program will fail for Maximum Subarray Sum 3(Kadane's Algo)
@akashmodak97 Yes. In case all array elements are negative the Kadane algo will fail. So in that case return the least negative number. Least negative number will be the answer.
No, I don’t think that the algorithm will fail, I pasted the right code for Kadane’s algo, that code will work fine for all kind of inputs and this code also follows Kadane algo’s logic.
Yeah okay…this algo will handle all negative numbers.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.