Maximum sub array

#include
using namespace std;
int main()
{

int n,a[100],cumsum[100]={0},currentsum,maxsum=0,f,l;
cin>>n;
cin>>a[0];
cumsum[0]=a[0];
for (int i=1;i<n;i++)
{
    cin>>a[i];
    cumsum[i]=cumsum[i-1]+a[i];
}
for(int i=0;i<n;i++)
{
    for(int j=i;j<n;j++)
    {currentsum=0;
        currentsum=cumsum[j]-cumsum[i-1];
        if (maxsum<currentsum)
        {
            maxsum=currentsum;
            f=i;
            l=j;
        }

    }

}
cout<<maxsum<<endl;
for (int k=f;k<=l;k++)
{
    cout<<a[k]<<",";
}
return 0;

}

what is the value of cumsum[i-1] when i=0???

Hello @saurabhsingh1625,

It will give garbage value because cSum[i-1] is cSum[-1].
cSum[-1] is a random value stored in memory at location prior to cSum[0].

The solution for that is:
Create the cSum[n+1] of size n;
and do
cSum[0]=0;
So, the formula will become:
currentSum = cSum[j+1] - cSum[i]

Hope, this would help.
give a like if you are satisfied.

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.