Cumulative sum of subarrays

#include
using namespace std;
int main(){
int cSum[100]={0},arr[100];
int n;
int left=-1,right=-1;
int currentSum=0,maximumSum=0;
cin>>n;
cin>>arr[0];
cSum[0]=arr[0];
for(int i=1;i<n;i++){
cin>>arr[i];
cSum[i]=cSum[i-1]+arr[i];
}
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(i==j)
currentSum=cSum[i];
else
currentSum=cSum[j]-cSum[i-1];

        if(maximumSum<currentSum)
        {
            maximumSum=currentSum;
            left=i;
            right=j;
        }
    }
}
cout<<maximumSum<<endl;
for(int i=left;i<=right;i++){
    cout<<arr[i]<<" ";

}

return 0;

}
if i starts with 0 the cSum[i-1]=0-1=-1then what will be the cSum[-1]

You cannot access negative indices, that’s why we are starting the for loop with i = 1

if my array is {12, -3 ,-4, 5 ,-7 } and i starts with 1;
then output will be wrong …
please give me accurate solution

@Satyamcoder why will your output be wrong? we are already storing the value of cSum[0] = a[0] before starting the for loop.


you can see mam

@Satyamcoder this is the correct answer as the whole array will be considered in this case (because it is the subarray with maximum sum, ie 17).

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.