Maximize K to make given array Palindrome when each element is replaced by its remainder with K | utility function to calculate the GCD of two numbers ; Function to calculate the largest K , replacing all elements of an array A by their modulus with K , makes A a palindromic array ; Check if A is palindrome ; A is not palindromic ; K can be infitely large in this case ; Variable to store the largest K that makes A palindromic ; Return the required answer ; Input ; Function call
function gcd ( a , b ) { if ( b == 0 ) return a ; else return gcd ( b , a % b ) ; } function largestK ( A , N ) { let l = 0 , r = N - 1 , flag = 0 ; while ( l < r ) { if ( A [ l ] != A [ r ] ) { flag = 1 ; break ; } l ++ ; r -- ; } if ( flag == 0 ) return - 1 ; let K = Math . abs ( A [ 0 ] - A [ N - 1 ] ) ; for ( let i = 1 ; i < N / 2 ; i ++ ) K = gcd ( K , Math . abs ( A [ i ] - A [ N - i - 1 ] ) ) ; return K ; } let A = [ 1 , 2 , 3 , 2 , 1 ] ; let N = A . length ; document . write ( largestK ( A , N ) + " " ) ;