What can be an efficient way to do this code, it gives a tle

#include
#include
using namespace std;

int main() {
int n,a[100],i,j,k,l,sum,max,t,x;
cin>>t;
for(x=1;x<=t;x++)
{
cin>>n;
for(i=0;i<n;i++)
cin>>a[i];
max=INT_MIN;

for(i=0;i<n;i++)
{
	for(j=i;j<n;j++)
	{
		sum=0;
		for(k=i;k<=j;k++)
		sum+=a[k];
		if(sum>max)
		max=sum;
		if(j==n-1)
		{
			for(l=0;l<i;l++)
			{
				sum=0;
				for(k=i;k<=j;k++)
					sum+=a[k];
				for(k=0;k<=l;k++)
					sum+=a[k];
				if(sum>max)
					max=sum;
			}
				
		}
		
	}
}
cout<<max;
}

return 0;

}

Hello @muskanrathore01_4aab76aa7dafc189,

  • Increase your array size from 100 to 1000.
  • Precompute prefix array sum which helps you to find the sum of a range in O(1)
    Efficient Code

I am not able to solve it I even used the approach by using kadane’s algorithm to reduce time complexity

#include #include using namespace std; int main() { int n,a[1000],i,j,k,l,sum,max,t,x,min,sum2,s1; cin>>t; for(x=1;x<=t;x++) { cin>>n; for(i=0;i<n;i++) cin>>a[i]; max=INT_MIN; min=INT_MAX; sum=0; for(i=0;i<n;i++) { sum+=a[i]; if(max<sum) max=sum; if(sum<0) sum=0; } sum2=0; for(i=0;i<n;i++) { sum2+=a[i]; if(min>sum2) min=sum2; if(sum2>0) sum2=0; } sum=0; for(i=0;i<n;i++) sum+=a[i]; s1=sum-min; if(s1==0) cout<<max; else if(s1>max) cout<<s1; else if(s1<max) cout<<max; } return 0; }

@muskanrathore01_4aab76aa7dafc189,

You need to print the max sum for each test case in a new line.
Change this:

 if(s1==0)
     cout<<max;
 else if(s1>max)
     cout<<s1;
 else if(s1<max)
     cout<<max;

to:

if(s1==0)
   cout<<max<<endl;
else if(s1>max)
   cout<<s1<<endl;
else if(s1<max)
   cout<<max<<endl;

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.