"How many inverted pairs" - that usually ends up with MergeSort solution (of course there are other solutions out there)
def mergeSort(arr): if len(arr) == 1: return 0, arr mid = len(arr) // 2 cnt1, arr1 = mergeSort(arr[:mid]) cnt2, arr2 = mergeSort(arr[mid:]) # ret = [] cnt = 0 i = 0 j = 0 inx = 0 while i < len(arr1) and j < len(arr2): if arr1[i] <= arr2[j]: ret.append(arr1[i]) i += 1 elif arr2[j] < arr1[i]: ret.append(arr2[j]) cnt += len(arr1) - i # arr2 -> arr1 j += 1 while i < len(arr1): ret.append(arr1[i]) i += 1 while j < len(arr2): ret.append(arr2[j]) j += 1 return cnt1 + cnt2 + cnt, ret T = int(input()) for _ in range(0, T): n = int(input()) arr = [int(i) for i in input().strip().split()] cnt, _ = mergeSort(arr) print (cnt)