Optimize nested loops for counting the total number of selections The question is: To select 2 numbers out of n positive integer inputs (order matters), where the number that is placed anywhere before the second must be greater than the second by a given number m. Count the total number of selections.
An example answer would be, given the inputs 5 1 3 2 4 and m is 0, the total number of selections is 5 (51,53,52,54,32)
Another example answer would be, given the inputs 6 5 4 3 2 1 and m is 2, the total number of selections is 6 (63,62,61,52,51,41)
How do I improve my double for-loop method in terms of time?
using namespace std;

int main()
{
    int n, m, i, j, m = 0, sum = 0;
    cin &gt;&gt; n &gt;&gt; m;
    int *a=new int[n];
    for (i = 0; i &lt; n; i++) {
        scanf(&quot;%d&quot;, &amp;a[i]);
    }
        
    for(i=0;i&lt;n-1;i++)
    {
        if (a[i] - m &lt;= 0)  continue;
        int temp=a[i]-m;
        for(j=i+1;j&lt;n;j++)
        if(a[j]&lt;temp) sum++;
    }
    cout&lt;&lt;sum&lt;&lt;endl;
    return 0;
}
`
using namespace std;


Don't do this.  We have namespaces for a reason, you know.  And we seem to be missing the necessary Standard Library headers &lt;iostream&gt; and &lt;cstdio&gt;.

    int n, m, i, j, m = 0, sum = 0;


These variable names tell us nothing about what they are used for.  Please use more expressive names.

    cin &gt;&gt; n &gt;&gt; m;


When reading from a stream such as std::cin, it's vital to check that the conversion was successful before using the values.  That could be as simple as
if (!cin) {
    return EXIT_FAILURE;
}


    int *a=new int[n];


Prefer a standard container (e.g. std::vector).

    for (i = 0; i &lt; n; i++) {


If we had a std::vector, we could have avoided hand-coding this loop:
auto a = std::vector{};
a.reserve(n);
std::copy_n(std::istream_iterator&lt;int&gt;(std::cin), n, a.begin());


        scanf(&quot;%d&quot;, &amp;a[i]);


Why are we mixing C++ streams and C stdio?  It's better to use just one (preferably the streams).  Again, we're missing the test whether the conversion was successful.