Make largest palindrome by changing at most K | Returns maximum possible palindrome using k changes ; Initialize l and r by leftmost and rightmost ends ; First try to make String palindrome ; Replace left and right character by maximum of both ; If k is negative then we can 't make  String palindrome ; At mid character , if K > 0 then change it to 9 ; If character at lth ( same as rth ) is less than 9 ; If none of them is changed in the previous loop then subtract 2 from K and convert both to 9 ; If one of them is changed in the previous loop then subtract 1 from K ( 1 more is subtracted already ) and make them 9 ; Driver code to test above methods
function maximumPalinUsingKChanges ( str , k ) { let palin = str . split ( " " ) ; let ans = " " ; let l = 0 ; let r = str . length - 1 ; while ( l < r ) { if ( str [ l ] != str [ r ] ) { palin [ l ] = palin [ r ] = String . fromCharCode ( Math . max ( str . charAt ( l ) , str . charAt ( r ) ) ) ; k -- ; } l ++ ; r -- ; } if ( k < 0 ) { return " " ; } l = 0 ; r = str . length - 1 ; while ( l <= r ) { if ( l == r ) { if ( k > 0 ) { palin [ l ] = ' ' ; } } if ( palin [ l ] < ' ' ) { if ( k >= 2 && palin [ l ] == str [ l ] && palin [ r ] == str [ r ] ) { k -= 2 ; palin [ l ] = palin [ r ] = ' ' ; } else if ( k >= 1 && ( palin [ l ] != str [ l ] palin [ r ] != str [ r ] ) ) { k -- ; palin [ l ] = palin [ r ] = ' ' ; } } l ++ ; r -- ; } for ( let i = 0 ; i < palin . length ; i ++ ) ans += palin [ i ] ; return ans ; } let str = " " ; let k = 3 ; document . write ( maximumPalinUsingKChanges ( str , k ) ) ;