```
def equal(lst):
temp=True
for i in range(len(lst)):
if lst[i]!=lst[0]:
temp=False
break
return temp
n=int(input())
for i in range(n):
num=int(input())
l=list(map(int,input().split()))
if equal(l)==True:
print(0)
else:
count=0
while True:
l[l.index(max(l))]=l[l.index(max(l))]-1
count=count+1
if equal(l)==True:
print(count)
break
```

count+=l[i]-min(l)

print count

I believe in case of else you are not terminating the while loop, pls check.

you can always optimize your code… my code works quiet similar to yours.

instead of subtracting 1 always my code subtracts second - max it to the max and store difference in ans variable…

i am not sure but i guess sys.stdin.readline is bit faster than normal input

here is AC code for 1.87sec

```
# cook your dish here
import sys
input = sys.stdin.readline
a = ''
for _ in range(int(input())):
n,l,ans = int(input()), sorted(list(map(int,input().split()))),0
while l[0] != l[-1]:
j = -2
while l[j] == l[-1]: j -= 1
ans += l[-1] - l[j]
l[-1] = l[j]
l = sorted(l)
a += str(ans)+'\n'
print(a)
```

and you should also understand that that sort, max, min, list.index and also your used defined function equal all have time complexity of O(n) and usage of these functions again and again might lead to a heavy computation. though constraints were small, still they make a huge deal.

you should look at ways to combine multiple operations need in one operation rather than doing them separately.