@mayank : The longest test case took 3 secs.
@Dilawar:
Each element can occur atmost two times .
___x__x___
Let s1,s2 be the number of elements smaller than x in red,yellow regions
b1,b2 be the number of elements bigger than x in yellow,pink regions
If we follow the algo I mentioned naively, we get a sum of s1(b1+b2) + b2(s1+s2) for these 2 positions of x.
s1*b2 is counted twice. So for each element that appears twice subtract from the sum the value of s1*b2.
For this we need to maintain the array positions of each value. I used a dict (defaultdict to be more precise) for that. That is not O(n) exaclty. But somewhere close (python uses hash for dicts).