text: Rearrange array to maximize sum of GCD of array elements with their respective indices | C # program to implement the above approach ; 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
code: using System ; class GFG { static int findMaxValByRearrArr ( int [ ] arr , int N ) { Array . Sort ( arr ) ; int res = 0 ; do { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += __gcd ( i + 1 , arr [ i ] ) ; } res = Math . Max ( res , sum ) ; } while ( next_permutation ( arr ) ) ; return res ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static bool next_permutation ( int [ ] p ) { for ( int a = p . Length - 2 ; a >= 0 ; -- a ) if ( p [ a ] < p [ a + 1 ] ) for ( int b = p . Length - 1 ; ; -- b ) if ( p [ b ] > p [ a ] ) { int t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . Length - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } return false ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 2 , 1 } ; int N = arr . Length ; Console . Write ( findMaxValByRearrArr ( arr , N ) ) ; } }