Infosys question for specialist programmer

Problem Statement

You will be given an array A of length N. You want to sort this array increasingly using the Magical Move as minimum as possible.

The Magical Move allows you to choose two different elements A[i] and A[j](1 <=i,j<= N) such that A[i]=A[j]+1 and make:

  • A[i] = A[i]
  • A[i] = A[i]-1

Your task is to find the minimum number of required Magical Moves to make the array sorted increasingly. Since the answer can be very large return it modulo 10^9+7.

Notes:

It is guaranteed that the given array is a permutation

Input Format

The first line contains an integer, N, denoting the number of elements in A Each line i of the N subsequent lines (where 0<=1<N) contains an integer describing All elements of array

Constraints : len of array : 1<=N<=10^5
1<=Arr[i]<=10^9

Test cases :
Input | Output

3 | 2
1
3
2

3 | 2
2
3
1

3 | 3
3
2
1

	s = sorted(a)
	counter = 0
	while s!=a:
		d = {}
		for i,v in enumerate(a):
			d[v]= i
			if v+1 in d:
				a[d[v+1]],a[d[v]] = a[d[v]],a[d[v+1]]
				break
		 else:
		 	return -1
		counter+=1
	return counter

I am getting TLE, help me out

Comments (1)