human
Rearrange array to maximize sum of GCD of array elements with their respective indices | Function to find the maximum sum of GCD ( arr [ i ] , i ) by rearranging the array.
Sort the array in ascending order.
Stores maximum sum of GCD ( arr [ i ] , i ) by rearranging the array elements.
Generate all possible permutations of the array.
Stores sum of GCD ( arr [ i ] , i ).
Traverse the array.
Update sum.
Update res.
Driver code"
How can the above be solved in Python?
assistant
#Here is code to rearrange array to maximize sum of GCD of array elements with their respective indices and the other steps required.
 def findMaxValByRearrArr ( arr , N ) :
	arr . sort ( )
	res = 0
	while ( True ) :
		Sum = 0
		for i in range ( N ) :
			Sum += __gcd ( i + 1 , arr [ i ] )
		res = max ( res , Sum )
		if ( not next_permutation ( arr ) ) :
			break
	return res
def __gcd ( a , b ) :
	if b == 0 :
		return a
	else :
		return __gcd ( b , a % b )
def next_permutation ( p ) :
	for a in range ( len ( p ) - 2 , - 1 , - 1 ) :
		if ( p [ a ] < p [ a + 1 ] ) :
			b = len ( p ) - 1
			while True :
				if ( p [ b ] > p [ a ] ) :
					t = p [ a ]
					p [ a ] = p [ b ]
					p [ b ] = t
					a += 1
					b = len ( p ) - 1
					while a < b :
						t = p [ a ]
						p [ a ] = p [ b ]
						p [ b ] = t
						a += 1
						b -= 1
					return True
				b -= 1
	return False
arr = [ 3 , 2 , 1 ]
N = len ( arr )
print ( findMaxValByRearrArr ( arr , N ) )