Max subarray sum, it gives 0 when all entries are -ve, shouldn't it give smallest no. instead?

#include
using namespace std;
int main() {
int t;
cin>>t;
while(t–)
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int curSum=0;
int maxSum=0;
for(int i=0;i<n;i++)
{
curSum+=a[i];
if(curSum<0)
{
curSum=0;
}
maxSum=max(curSum,maxSum);
}
cout<<maxSum<<endl;
}
return 0;
}

hello @ganesh2512

u can modify its implementation a bit , to make it work for evry cases.

int max_so_far      = array[0];
int max_ending_here = 0;


for (int i = 0; i < size; i++)
{
    max_ending_here =max_ending_here + array[i];
    max_so_far      = max(max_ending_here, max_so_far);
    max_ending_here = max(max_ending_here, 0);

}

suppose array set is: -7,-5,-2,-4,-8

then it should give -2 as o/p, but it is not

i have shared the correct implementation in my first response itself pls check.

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.