Maximum sub array sum

what is the problem with my code it’s giving wrong answer

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

int main()
{
long long int t;
cin>>t;
while(t–)
{
long long int n,i,j,f=0,g=0;
cin>>n;
long long int a[n]={0};
long long int s[n+1]={0};
for(i=0;i<n;i++)
{
cin>>a[i];
s[i+1]=s[i]+a[i];
if(a[i]<0)
{
f=1;
}
else
{
g=1;
}
}
if(g==1&&f==0)
{
cout<<s[n]<<endl;
}
else if(f==1&&g==0)
{
cout<<*max_element(a,a+n)<<endl;
}
else
{
long long int ans=s[n];
i=0;
j=n-1;
while(i<=j)
{
while(a[i]<0)
{
i++;
}
while(a[j]<0)
{
j–;
}
if(i<=j)
{
if(s[j+1]-s[i]>ans)
{
ans=s[j+1]-s[i];
}
}
if(a[i]>a[j])
{
j–;
}
else
{
i++;
}
}
cout<<ans<<endl;
}
}
return 0;
}

#include <bits/stdc++.h> using namespace std; int main() { long long int t; cin>>t; while(t–) { long long int n,i,j,f=0,g=0; cin>>n; long long int a[n]={0}; long long int s[n+1]={0}; for(i=0;i<n;i++) { cin>>a[i]; s[i+1]=s[i]+a[i]; if(a[i]<0) { f=1; } else { g=1; } } if(g==1&&f==0) { cout<<s[n]<<endl; } else if(f==1&&g==0) { cout<<*max_element(a,a+n)<<endl; } else { long long int ans=s[n]; i=0; j=n-1; while(i<=j) { while(a[i]<0) { i++; } while(a[j]<0) { j–; } if(i<=j) { if(s[j+1]-s[i]>ans) { ans=s[j+1]-s[i]; } } if(a[i]>a[j]) { j–; } else { i++; } } cout<<ans<<endl; } } return 0; }

@harry_potter123,
Please use Coding Blocks IDE to share your code. See yourself above, are you able to read the code yourself.
Shouldn’t the answer when all negative elements are present, be max{a[i]}…??

why it is giving Wrong answer

@harry_potter123,
Why aren’t you using kadane’s algorithm? Consider using it, this problem can’t be solved greedily, like you are trying to, it requires dp.

Anyways, your code gives wrong answer on,

Input:
1
5
1 2 3 -14 2

i dont know about kadanes algo pls explain

@harry_potter123,
It must be in the dp section pf your course, if you haven’t reached there till now, then leave this problem for now. You will be taught Kadane’s in your course. You can try this problem then.

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.