Form the largest palindromic number using atmost two swaps | function to form the largest palindromic number using atmost two swaps ; if length of number is less than '3' then no higher palindromic number can be formed ; find the index of last digit in the 1 st half of ' num ' ; as only the first half of ' num [ ] ' is being considered , therefore for the rightmost digit in the first half of ' num [ ] ' , there will be no greater right digit ; index of the greatest right digit till the current index from the right direction ; traverse the array from second right element in the first half of ' num [ ] ' up to the left element ; if ' num [ i ] ' is less than the greatest digit encountered so far ; there is no greater right digit for ' num [ i ] ' ; update ' right ' index ; traverse the ' rightMax [ ] ' array from left to right ; if for the current digit , greater right digit exists then swap it with its greater right digit and also perform the required swap operation in the right halft of ' num [ ] ' to maintain palindromic property , then break ; performing the required swap operations ;  ; Driver code ; required largest palindromic number
function largestPalin ( num , n ) { if ( n <= 3 ) return ; let mid = Math . floor ( n / 2 ) - 1 ; let rightMax = new Array ( mid + 1 ) ; let right ; rightMax [ mid ] = - 1 ; right = mid ; for ( let i = mid - 1 ; i >= 0 ; i -- ) { if ( num [ i ] < num [ right ] ) rightMax [ i ] = right ; else { rightMax [ i ] = - 1 ; right = i ; } } for ( let i = 0 ; i <= mid ; i ++ ) { if ( rightMax [ i ] != - 1 ) { swap ( num , i , rightMax [ i ] ) ; swap ( num , n - i - 1 , n - rightMax [ i ] - 1 ) ; break ; } } } function swap ( arr , i , j ) { let temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; return arr ; } let num = " " . split ( " " ) ; let n = num . length ; largestPalin ( num , n ) ; document . write ( " " + ( num ) . join ( " " ) ) ;