Count number of previous elements greater than its element at present index Suppose I have a vector containing n elements. I want to find out the number of previous elements greater than its element at present index i. I want to find A[i] &gt; A[j] &amp;&amp; i &lt; j for all elements of the vector.

Constraints:

1 &lt;= t &lt;= 1000
1 &lt;= n &lt;= 10^5
1 &lt;= A[i] &lt;=10^5


My code:

#include&lt;bits/stdc++.h&gt;
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin &gt;&gt; t;

    while(t--) {
        int n,a,i,j;
        cin &gt;&gt; n;

        vector&lt;int&gt;v1;

        for(i=0;i&lt;n;i++) {
            cin &gt;&gt; a;
            v1.push_back(a);
        }
        int cnt=0,sum=0;

        for(i=0;i&lt;n;i++) {
            if( i!=0) {
                for(j=0;j&lt;i;j++) {
                    if(v1[i]&lt;v1[j]) {
                        cnt++;
                    }
                }
            }
            //  cout &lt;&lt; cnt &lt;&lt; " ";
            sum=sum+cnt;
            cnt=0;
        }

        cout &lt;&lt; sum &lt;&lt; '\n';
    }
}


This code is running fine for all the test cases except only one. It is showing the Time limit exceeded for one of the test cases. Can anyone help me?
I don't think there is a logic error in what you have posted. And even though there are details that would make it nicer (the cycle can for example run from i=1, questionable use of bits/stdc++.h header, long variable scopes and similar), it should do its job.

I suggest to think about time complexity of the algorithm. Your brute force approach will have quadratic complexity and may be too slow when the input is large.

There are different approaches that you can try. For example, I see you tagged your post with binary-search tag. Why? You could for example keep your vector sorted as the user enters the values. When adding a new number, find where it belongs (you can do it by bisection - with logarithmic complexity). All numbers to the left are smaller, the ones on the right are larger. Then insert the number and repeat. How to do it exactly is up to you, if you're allowed to use C++ algorithms, std::lower_bound and std::vector::insert will do the hard work for you.

You can of course craft some tree structure of your own to do something along those lines.