Kaydane algo is not working on negative array

#include
#include

using namespace std;

int maxSubarray(int a[], int n)
{
int currentSum = 0, maxSum = 0;
for (int i = 0; i < n; i++)
{
currentSum = currentSum + a[i];
if (currentSum < 0)
{
currentSum = 0;
}
maxSum = (max(maxSum, currentSum));

}
return maxSum;

}
int main()
{

int n;

cout << "Enter the size of array";
cin >> n;
int a[n];

cout << "enter the elements" << endl;
for (int i = 0; i < n; i++)
{
    cin >> a[i];
}

cout<<maxSubarray(a, n);

}

Hello @anandsingh3210 if all the elements in the array are negative then the answer should be zero what your code is givig the result?

I have just checkde your code is giving the correct result for all the negative numebrs in the array like you can see:


when all the elements are naegative then the subarray with maximum sum will be with no elements and then the subarray sum will b e zero.
if you have any doubt you can ask here:
Happy Learning!!

but sir techinically if the array is totally negative then the output should be least negative number closer to 0.

But here in the question it is mentioned that we have to find the maximum sum possible and kadanes algo is also define for such way only where incace of negative elements it will give zero as the answer because maximum is zero only it can find.
if you still have any doubt you canask here:
Happy Learning!!

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.