Time limit exceeding

#include
#include
using namespace std;

int circular(int arr[], int n)
{
int total = 0;
int max_so_far = arr[0];
int min_so_far = arr[0];
int max_here = arr[0];
int min_here = arr[0];

	for(int i = 0;i < n;i++){
		total += arr[i];}
		for (int i = 1; i < n; i++){
		max_so_far = max(max_so_far+arr[i], arr[i]);
		max_here = max(max_so_far, max_here);

		min_so_far = min(min_so_far+arr[i], arr[i]);
		min_here = min(min_so_far, min_here);		
	}	
	if(min_here == total)
		return max_here;
	return max(max_here, total-min_here);

}

int main() {
int t, n;
cin >> t;
while(t–){
cin >> n;
int *arr = new int[n];
for(int i = 0;i < n;i++){
cin >> arr[i];
}
int max = circular(arr, n);
cout << max;
}
return 0;
}

why is compilation giving tle?

hello @ayushi1150
make sure u r giving input ,before running ur program…

also pls share ur code using cb ide

Sir i am giving input before running the program

ok ,please share ur code using cb ide

where should i share the code ?

save ur code here->https://ide.codingblocks.com/
and then share the genrated link with me

sorry i am sending again

@ayushi1150
ur solution time complexity is O(t*n^2) which is the reason for tle .

u need to use O(n) approach for solving this problem
refer this->

The maximum subarray sum in circular array is maximum of following

  • Maximum subarray sum in non circular array
  • Maximum subarray sum in circular array.

Example - [1,2,5,-2,-3,5]
Steps -

  • Find the maximum subarray sum using Kadane Algorithm. This is maximum sum for non circular array.

  • 1+2+5 = 8
  • For non circular sum,
    Step 1) find the minimum subarray sum of array.

-2-3 = -5
Step 2) Now find the total sum of array = 1 + 2 + 5 -2 - 3 + 5 = 8
Step 3) The max subarray sum for circular array = Total Sum - Minimum subarray Sum
= 8 - (-5) = 8 + 5 = 13
As illustrated above, substracting minimum subarray sum from total sum gives maximum circular subarray sum.
Answer = Max ( Non circular max sum + circular max sum ) = max(8,13) = 13

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.

Sir i am getting wrong ans and tle warning again

https://ide.codingblocks.com/s/350516 this is the code

Sir what should i do now??

Looking into it ,wait

Hey @ayushi1150
Updated ur code and mentioned the changes in comments: https://ide.codingblocks.com/s/350523 :slight_smile:
If u dont understand the change then let me know.
Otherwise please close this :slight_smile: