Rainwater harvesting problem ,Why is it showing TLE in 3 test cases

void pairedElements( int arr[],int n)
{
int sum=0;
for(int i=1;i<n-1;i++){
int lm=0, rm=0;
for(int k=0;k<i;k++)lm=max(arr[k],lm);
for(int k=i+1;k<n;k++)rm=max(arr[k],rm);

   int f=min(rm,lm)-arr[i];
   //cout<<lm<<" "<<rm<<endl;
   if(f>0)sum+=f;

}
cout<<sum;
}

Hello @argus he appoach which you are trying is not the optimised one:
that is why it is giving TLE in some cases.
you have to optimise your code as the test cases are larger.
see this code:


if you have any doubt you can ask here:
Happy Learning!!

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.