Maximum subarray sum

#include <bits/stdc++.h>

using namespace std;
int kadane(int a[],int n)
{
int currSum=0;
int maxSum=0;
for(int i=0;i<n;i++){
currSum = currSum + a[i];
if(currSum < 0){
currSum = 0;
}
maxSum = max(currSum,maxSum);
}
return maxSum;
}
int circularSum(int a[],int n){
int c1 = kadane(a,n);
int c2=0;
for(int i=0;i<n;i++){
c2 += a[i];
a[i]=-a[i];

}
c2 = c2 + kadane(a,n);
return (c2 > c1) ? c2:c1;
int main(){
int t;
cin>>t;
for(int i=0;i<t;i++){
int a[1000];
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
cout<<circularSum(a,n)<<endl;
}
return 0;
}

why is it necessary to give a[i]=-a[i]? PLease explain briefly with example…

@Ambuj-Singh-514796906079795 hey here 2 cases arise:
Case 1: The elements that contribute to the maximum sum are arranged such that no wrapping is there. Examples: {-10, 2, -1, 5}, {-2, 4, -1, 4, -1}. In this case, Kadane’s algorithm will produce the result.

Case 2: The elements which contribute to the maximum sum are arranged such that wrapping is there. Examples: {10, -12, 11}, {12, -5, 4, -8, 11}. In this case, we change wrapping to non-wrapping. Let us see how. Wrapping of contributing elements implies non wrapping of non contributing elements, so find out the sum of non contributing elements and subtract this sum from the total sum. To find out the sum of non contributing, invert sign of each element and then run Kadane’s algorithm.
Our array is like a ring and we have to eliminate the maximum continuous negative that implies maximum continuous positive in the inverted arrays.

Finally we compare the sum obtained by both cases, and return the maximum of the two sums.

I am just asking how will a[i]=-a[i] work in the code given above??

@Ambuj-Singh-514796906079795 hey that is also explained in step 2 please read it carefully ,o find out the sum of non contributing, invert sign of each element as we have to find sum of elements opposite to contributing elements so invert sign.

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.