Problem Statement:
Watson gives Sherlock an array \$A_1\$, \$A_2\$ ... \$A_N\$. He asks him to find an integer \$M\$ between \$P\$ and \$Q\$ (both inclusive), such that, \$\min \{|A_i-M|, 1 \le i \le N\}\$ is maximised. If there are multiple solutions, print the smallest one.
Input Format:
The first line contains \$N\$. The next line contains space separated N integers, and denote the array \$A\$. The third line contains two space separated integers denoting \$P\$ and \$Q\$.
Constraints:
- \$1 \le N \le 10^2\$
- \$1 \le A_i \le 10^9\$
- \$1 \le P \le Q \le 10^9\$
My code:
#include <bits/stdc++.h>
int main()
{ int size,print,dist=INT_MIN,answer,start,end,diff;
std::vector <int> arr;
std::cin>>size;
for(int i=0;i<size;i++)
{ int templ
std::cin>>temp;
arr.push_back(temp);
}
std::sort(arr.begin(),arr.end());
std::cin>>start>>end;
for(int i=start;i<=end;i++)
{
dist=INT_MAX;
for(int j=0;j<size;j++)
{
diff=fabs(i-arr[j]);
if(diff>dist)
break;
dist=std::min(dist,diff);
}
if(dist>answer)
{
answer=dist;
print=i;
}
}
std::cout<<print;
return 0;
}
My code is producing the output that I'm expecting, however it is failing with the hackerrank judge telling me that the time limit has been exceeded.
According to me its running time is O(n(p-q)). Then it should clear all the test cases in less than 2s (assuming computer can compute 10^9 problems in a second, I remember reading somewhere that that's how most online judges work). At most my program will work on 10^11 problems (n*p-q= 10^2 *10^11).
Do my timing predictions make sense?
How can I improve my code, particularly the performance so that it is able to pass this judge?