Testcase is failing with TLE error

#include
#include

using namespace std;

int main() {
int lmax, rmax, N;
long int count=0;
cin >> N;
if(N == 1)
{
cout << “0”;
return 0;
}

int arr[N];
for(int i=0; i<N; i++)
	cin >> arr[i];

for(int i=1; i<N-1; i++)
{
	lmax = *max_element(arr, arr+i);
	rmax = *max_element(arr+i, arr+N);
	if((min(lmax, rmax) - arr[i]) > 0)
		count = count +  min(lmax, rmax) - arr[i];
}
cout << count;
return 0;

}

Hey @mramanjain please share your code using ide.codingblocks.com, if you don’t know how to do it. You can also ask me that.

Hey you are getting tle because of the approach you are using, as max_element(arr, arr+N) takes O(n) time to find the maximum element in the partition of array you wanted. And you are doing it n times so your complexity becomes O(NN) , instead do it with array and store them
Take this for reference

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.