I have compiled the same code in vscode, it is running properly,pls help me finding out the problem here

#include
#include
using namespace std;
void circulararray(){
int n;
cin>>n;
int size=(2*n)-1;
int a[size];
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=n;i<size;i++){
a[i]=a[i%n];
}
int max=INT_MIN;
for(int i=0;i<size;i++){
for(int j=i;j<size;j++){
int sum=0;
for(int k=i;k<=j;k++){
sum+=a[k];
if(sum>max){
max=sum;
}
}
}

}cout<<max;

}
int main() {
int testcase;
cin>>testcase;

while(testcase!=0){

    circulararray();
    testcase--;
}

return 0;

}

hi @rounaqkhandelwal24
This Question can be done using the brute force viz, by using two nested loops and checking the sum of every possible subset but this approach is in O(n^2). So, Now we are going to discuss an approach which solves the given problem in O(n).

Approach :
For finding the Maximum Contiguous sum we are using the kadane’s algorithm. But in the question the array is circular that means the maximum sum can be of elements which are a part of the wrapping or not. So,
There can be two cases for the maximum sum:
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.

refer this code -->

but what have i done here is, that i made my array with size 2n-1; so that circular maximum sum can be easily constructed

hi @rounaqkhandelwal24
ur logic is not correct… hence it fails on some test cases…
consider this

1
5
1 2 3 4 5

ur code gives o/p as 25, while expected is 15…
refer the code and explanation I sent above…

@rounaqkhandelwal24


u can refer this video lecture for better understanding…

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.