Please help me resolve the issue in my code

question link :
my submission link :
it’s failing last two hidden test cases
in case the link for submission dosen’t work this is my code:
‘’‘n = int(input())
strength = list(map(int, input().split()))
profit = 0
for i in range(n):
for j in range(i+1, n):
profit += abs(strength[i] - strength[j])

It should be:
profit+=(freq[i] * freq[j]) * (j-i)

1 Like

Sorry but i don’t think that it is correct.
Moreover to confirm it i checked it by putting it in my code now it passes 0 test cases. :slight_smile:

I have updated the statement: You must calculate the frequence of the array elements and then the above. Here is my solution for your reference

1 Like

i only know python so i’m not able to understand your code could you translate it.

Here is the equivalent in python

1 Like

can you please explain what this line means
ans += abs(j - i) * mp[i] * mp[j]
and also that what is the fault in my code

@lokendrayadav join me on discord my username and tag is HunterSoulz#9312

If you observe clearly, we are finding the sum of absolute difference of each pair in the array. So, I calculated the frequency of each element present in the array and the answer is the difference of the positions along with the strengths given.
Alternatively, this can also be done is O(n). We can first sort the given array and take the difference between the ith position and (n-i-1)th position i.e.
Now for your code- You are running a O(n^2) loop and N is given 2*10^5, so it will given TLE

1 Like

Thank You !!! :wink: :wink:

but how does ‘‘ans += abs(j - i) * mp[i] * mp[j]’’ <== gives us the abs difference between each pair?