for _ in range(int(input())):
num=int(input())
a=list(map(int,input().split()))[:num]
sum=0
for i in range(len(a)):
j=a[i]
count=0
key=0
for k in range(len(a)):
if j==a[k]:
key=k
sum+=abs(key-i)
print(sum)
Given an integer array. The task is to calculate the sum of absolute difference of indices of first and last occurrence for every integer that is present in the array.
Required to calculate the sum of the answer for every such that occurs in the array.
One input:
1 2 3 3 2
Sample Output:
4
Explanation: The elements which occur in the array are 1,2,3.
- it has only occurred once so the answer for 1 is 0.
- it has two occurrences at 2 and 5 so |5-2|=3
- it has two occurrences at 3 and 4 so |4-3|=1.
So total sum=0+3+1=4.
p.s: The first loop is for test cases.
Pleae suggest me to reduce time-complexity.