CPP- Maximum Subarray Sum 3(Kadane's algo)

In the video you have initialized current sum as 0 and maxSum as 0.
But I think the maxsum should be initialized to INT_MIN value so that the code works for only negative values too.

@tanmayrajDTU
Every array always has a NULL subarray. The NULL subarray is the subarray having no elements in it. Consequently its sum is considered to be 0. Hence the minimum answer that you could get from Kadane’s Algo for an array with all -ve elements would still be 0 due to the presence of NULL subarray. However if you do not wish to consider it and want a non-zero value for the case of all -ve numbers array as well , you should consider computing the largest element of the array. This can be done in the very same loop , just make a new variable for it. Let’s call this value as maxOfArray. Also you have the maxSum value computed using the Kadane’s Algo. Now just check if maxSum is equal to 0. If it is , print maxOfArray. Else print maxSum.

1 Like

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.