Can anyone please help me regarding time complexity, I knew basic of them n(O) and all but how does this online compiler really decides the time complexity of code, please explain in details like whether it depends on input, output, datatype, loops and all. I am using c++.
For example consider this two code.
//////////////////////////////////////////////////////////////////////
Code 1.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
for(int i=0;i<t;i++)
{
int n;
cin>>n;
long long arr[n];
for(int j=0;j<n;j++)
{
cin>>arr[j];
}
sort(arr,arr+n);
long long min1=arr[0];
long long diff=0;
for(int j=1;j<n;j++)
{
diff=diff+(arr[j]-min1);
}
cout<<diff<<endl;
diff=0;
}
}
//////////////////////////////////////////////////////
Code 2.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t–)
{
int n,count=0;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
sort(arr, arr+n);
for(int i=1;i<n;i++)
count = count + (arr[i] - arr[0]);
cout<<count<<endl;
}
return 0;
}
//////////////////////////////////////////////////
Here the first code runs fine but second code throws time limit exceed RTE.
Also if shift the input in while loop of test case than it works fine
like this:
while(t-- && cin>>n)
{
//code
}
why so…?
Please help me.
Thank You