Maximum Circular Sum

I am doing this question using 3 for loops by resetting the pointer j and k whenever they exceed the size of the array. I am getting TLE in 1 test case.

#CODE

using namespace std;
int main() {
int Test;
cin >> Test;
while(Test–) {
int n, arr[1000];
cin >> n;
for(int i = 0; i < n; i++) {
cin >> arr[i];
}
int maxSum = INT_MIN;
// i loop
for(int i = 0; i < n; i++) {
int j = i;
// j loop
do{
int sum = 0;
// k loop
int k = i;
while(k != j) {
sum = sum + arr[k];
k++;
if(k == n) {
k = 0;
}
}
sum = sum + arr[k];
if(sum > maxSum) {
maxSum = sum;
}
j++;
if(j == n) {
j = 0;
}
} while(j != i);
}
cout << maxSum << endl;
}
return 0;
}

Also, I was trying to do this question using the cumulative sum approach but I am not getting the correct answer.

Can you please help me out here
Thank you

hi @Vinayak-Bhardwaj,
one suggestion please try avoiding do while loop in program it is very difficult to keep track of the code even in dry run.
since it is a circular array we can understand it as 2 cases if max sum subarray is present normally or there is a wrap around condition.

So first unfold the array i.e make another array of size 2*n and repeat the array in that
eg if arr is [1,2,3] make brr as [1,2,3,1,2,3]
now this brr array is unfolded. Now try finding max sum subarray in every continuous window of size n (original)
here wrap around condition will also be covered
eg arr is [1,-50,10] then brr will be [1,-50,10,1,-50,10] so we will get [10,1] which is wrapped from last to start of array arr
you can refer this https://ide.codingblocks.com/s/658419 ive commented the code

1 Like

Thank you so much @talhashamim001 for the explanation

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.