Max subarray sum that can contain negative elements as well. The code is working but the test cases are not getting passed. What am I doing wrong? (Ik the code's a little messy but still it should work according to me.)

#include
#include
#include<bits/stdc++.h>
using namespace std;

int sub(int a[1000], int m)
{
int check,sum[1000];
int maxi = INT_MIN;
if(a[0]>=0)
{
sum[0]=a[0];
}
else
{
sum[0]=0;
}
for(int i=1;i<m;i++)
{
check = a[i]+sum[i-1];
if(check<0)
{
sum[i]=0;
}
else
{
sum[i]=check;
}
maxi = max(maxi,sum[i]);
}
if(maxi==0)
{
maxi=a[0];
for(int i=1;i<m;i++)
{
maxi = max(maxi,a[i]);
}
return maxi;
}
else{
return maxi;}
}

int main()
{
int n,a[1000],sum[1000];
cin>>n;
int m;

for(int j=0; j<n; j++)
{
    cin>>m;
for(int i=0;i<m;i++)
{
    cin>>a[i];
}
  	sum[j]=sub(a,m);
}

for(int j=0; j<n; j++){
    cout<<sum[j]<<endl;
}
return 0;

}

@abhi18sinha please share it using cb ide


This is the link to the code

@abhi18sinha ok wait let me check

@abhi18sinha its fine just increased size and passed array correctly


corrected and commented

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.