You are given an array “balls” denoting the size of each ball. You need to calculate the sum of shadow balls for all the balls present in the array.
For Example :arr = {3, 5, 1, 4}
In this example, the shadow of ball 3 -> 1.
The shadow of ball 5 -> 1.
Hence the total number of shadows are 1 + 1 = 2.
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows:
The first line of each test case contains a single integer ‘N’ denoting the total number of balls.
The next line contains ‘n’ integers denoting the size of each ball.
Output Format :
For each test case, print a single integer “ans” denoting the sum of shadow balls for all the balls.
Output for each test case will be printed in a separate line.
Note :
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N <= 5000
1 <= balls[i] <= 10^5
Time limit: 1 sec
2
4
3 5 9 11
3
7 5 3
0
3
In the first test case, there is no ball having a shadow ball.
Hence, the answer is 0.
In the second test case, the shadow of ball 7 -> 5, 3 and the shadow of ball 5 -> 3.
Hence the answer is 3.
2
5
1 5 6 4 20
3
1 2 3
2
0
Find all the balls having a size less than the current ball using brute force.
In this approach, We will iterate through the array, and for each element of the array, check all the elements with greater index, having a size less than the current element.
The steps are as follows:
O( N ^ 2 ), where N is the size of the array “balls”.
As we are iterating through the array in a nested manner.
Hence the time complexity is O( N ^ 2 ).
O( 1 )
No extra space is used.
Hence the space complexity is O(1).