Code for calculating number of variations 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 &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;cmath&gt;
#include &lt;algorithm&gt;


std::vector&lt;int&gt;loadTestCases(int N){
    std::vector&lt;int&gt; testCases;
    for (int i = 0; i &lt; N; i++)
    {
        int TestCase;
        std::cin &gt;&gt; TestCase;
        testCases.push_back(TestCase);
    }
    return testCases;
}

int main(){

    int args,k;
    std::cin &gt;&gt; args &gt;&gt; k;

    std::vector&lt;int&gt; nums = loadTestCases(args);
    int cases = 0;

    sort(nums.begin(),nums.end());


    for(int i=1;i&lt;args;i++){
        int temp = std::abs(nums.at(i)-nums.at(i-1));
        if(temp &gt;=k){
            cases = cases + i;
        }else{
            int j = i;
            while(temp &lt; k &amp;&amp; j &gt; 0){
                j--;
                temp = std::abs(nums.at(i)-nums.at(j));
            }
            if(temp &gt;= k){
                cases = cases + j + 1;
            }
        }
    }

    std::cout &lt;&lt; cases &lt;&lt; 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?
Similar to the other question, I would suggest to utilize a std::map changing your loadTestCases accordingly

std::map&lt;int, int&gt;loadTestCases(int N){
    std::map&lt;int, int&gt; testCases;
    int TestCase;
    for (int i = 0; i &lt; N; i++)
    {
        std::cin &gt;&gt; TestCase;
        auto inserted = testCases.emplace(TestCase, 1);
        if(!inserted.second) {
            testCases.at(TestCase)++;
        }
    }
    return testCases;
}


The advantage of this approach is, that you only have to traverse the keys of the std::map once and can multiply the values if there is a match.

Also given that your container is sorted you can actually skip the std::abs call, as a_i - a_j > 0 is guaranteed by that sort, if you traverse the container from the back. Also more importantly, once you find a_i - a_l > k, you automatically know, that any following pair is also valid, as by construction for an a_m &lt; a_l we get a_i - a_m = a_i - a_l - (a_m - a_l), with (a_m - a_l) &lt; 0.