Form the largest palindromic number using atmost two swaps | Java implementation to 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
class GFG { static void largestPalin ( char num [ ] , int n ) { if ( n <= 3 ) return ; int mid = n / 2 - 1 ; int [ ] rightMax = new int [ mid + 1 ] ; int right ; rightMax [ mid ] = - 1 ; right = mid ; for ( int i = mid - 1 ; i >= 0 ; i -- ) { if ( num [ i ] < num [ right ] ) rightMax [ i ] = right ; else { rightMax [ i ] = - 1 ; right = i ; } } for ( int i = 0 ; i <= mid ; i ++ ) { if ( rightMax [ i ] != - 1 ) { swap ( num , i , rightMax [ i ] ) ; swap ( num , n - i - 1 , n - rightMax [ i ] - 1 ) ; break ; } } } static char [ ] swap ( char [ ] arr , int i , int j ) { char temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; return arr ; } public static void main ( String [ ] args ) { char num [ ] = "4697557964" . toCharArray ( ) ; int n = num . length ; largestPalin ( num , n ) ; System . out . println ( " Largest ▁ Palindrome : ▁ " + String . valueOf ( num ) ) ; } }