Not getting desired output for input 1,2,3,4,5

//cummulative sum approch
#include<iostream>
#include<climits>
using namespace std;
int main()
{    
int a[100]={0};
int cumsum[100]={0};
int n;
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];
	}
int maxsum=INT_MIN;
int currsum=0;
for(int i=0;i<n;i++)
{
	for(int j=i;j<n;j++)
	{  currsum=cumsum[j]-cumsum[i-1];
		maxsum=max(currsum,maxsum);
		currsum=0;
		}
	}
	cout<<maxsum;

return 0;
}

Hello @sagar_aggarwal,

the value of cumsum[i-1] when i=0 will give garbage value because cumsum[i-1] is cumsum[-1].
cumsum[-1] is a random value stored in memory at location prior to cumsum[0].

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

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

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.