Both codings are solution to same ques .Can somebody explain me why 1st code is showing time limit exceeded (TLE) error and 2nd code doesnot?

#include<stdio.h>
#define c 1000000007
int main()
{
int t;
long int n;
scanf("%d",&t);
while(t>0)
{
scanf("%ld",&n);
long int p[n];
for(int i=0;i<n;i++)
{
scanf("%ld",&p[i]);
}
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
long int temp;
if(p[j]<p[j+1])
{
temp=p[j+1];
p[j+1]=p[j];
p[j]=temp;
}
}
}
int profit=0;
for(int x=0;x<n;x++)
{
int h=p[x]-x;
if(h>0)
{
profit=((profit%c)+(p[x]%c)-(x%c))%c;
}
else
break;
}
printf("%d\n",profit%c);
t–;
}
}

OR

#include <bits/stdc++.h>
#include
#include
#include

using namespace std;

int main()
{
int t;
ios_base::sync_with_stdio(false);cin.tie(NULL);
cin>>t;
while(t–){
long long int n,d=0,p=0;
vector prices;
cin>>n;
for(long long int i=0; i<n; i++){
int b;
cin>>b;
prices.push_back(b);
}
sort(prices.begin(),prices.end(),greater());
for(long long int j=0; j<n; j++){
if(prices[j]-d>0){
p+=prices[j]-d;
}
d++;
}
cout<<p%((int)pow(10, 9)+7)<<endl;
}
}

First of all format your code by placing it inside ``` and ``` or just give a link to the code
It is really hard to see with the weird indentation you have.

As far as I can see, it seems like the first one is using Bubble sort to sort the arrays and the second one uses std::sort which is inbuilt in c++.

The time complexity of first one will be O(n^2) and second one is O(nlogn)
That is why you are getting TLE in the first one.

1 Like

ok, i got it. Now, i got the reson. Thanks