Code of maximum subarray 2

#include
using namespace std;
int main()
{
int n,current_sum=0,maximum_sum=0,left,right;
cin>>n;
int a[1000];
cin>>a[0];
int cumsum[1000];
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++)
{
current_sum=cumsum[j]-cumsum[i-1];
if(current_sum>maximum_sum)
{
maximum_sum=current_sum;
left=i;
right=j;
}
}
}
cout<<“maximum sum is: “<<maximum_sum<<endl;
for(int i=left;i<=right;i++)
cout<<a[i]<<”,”;
return 0;
}

@jindaldivish
hello divish,
what issue u r facing?

what will happen when the nested for loop will execute and value of i=0

When i=0 cumsum[i-1]; will be cumsum[-1]. The compiler automatically assigns cumsum[-1] as 0 and the code runs correctly without error. You can check that on your own.

but we know that we can’t access negaitve indices of the array , then how can compiler assigns cumsum[-1]=0

Ye you are correct and you should prevent using negative indexes in C++ but newer versions of compiler supports and does not throw an error.
Check this https://ide.codingblocks.com/s/200734

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.