Following up from my previous question where I put up a solution in brute for algorithm to this problem from codechef.
Given some number \$K\$ and a list of \$N\$ numbers, count the number of pairs (\$i\$, \$j\$) such that \$1 \le i \lt j \le N\$ and \$|a_i − a_j | \ge K\$.
- \$1 \le N \le 65000\$
- \$1 \le K \le 10^8\$
- \$0 \le a_i \le 10^8\$
I changed my code quite a bit and was able to get rid of that time-limit-exceded
error.Thanks to the responses, here is the updated code:
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
std::vector<int>loadTestCases(int N){
std::vector<int> testCases;
for (int i = 0; i < N; i++)
{
int TestCase;
std::cin >> TestCase;
testCases.push_back(TestCase);
}
return testCases;
}
int main(){
int args,k;
std::cin >> args >> k;
std::vector<int> nums = loadTestCases(args);
int cases = 0;
sort(nums.begin(),nums.end());
for(int i=1;i<args;i++){
int temp = std::abs(nums.at(i)-nums.at(i-1));
if(temp >=k){
cases = cases + i;
}else{
int j = i;
while(temp < k && j > 0){
j--;
temp = std::abs(nums.at(i)-nums.at(j));
}
if(temp >= k){
cases = cases + j + 1;
}
}
}
std::cout << cases << std::endl;
return 0;
}
But according to me the code still looks a little ugly and can be optimized more , can someone help me to identify the parts where simplification without risking the time taken can be done?