Find the largest number that can be formed by changing at most K digits | Java implementation of the approach ; Function to return the maximum number that can be formed by changing at most k digits in str ; For every digit of the number ; If no more digits can be replaced ; If current digit is not already 9 ; Replace it with 9 ; One digit has been used ; Driver code
class GFG { static StringBuilder findMaximumNum ( StringBuilder str , int n , int k ) { for ( int i = 0 ; i < n ; i ++ ) { if ( k < 1 ) break ; if ( str . charAt ( i ) != '9' ) { str . setCharAt ( i , '9' ) ; k -- ; } } return str ; } public static void main ( String [ ] args ) { StringBuilder str = new StringBuilder ( "569431" ) ; int n = str . length ( ) ; int k = 3 ; System . out . println ( findMaximumNum ( str , n , k ) ) ; } }