Find the maximum difference after applying the given operations two times on a number | Java program to find the maximum difference after two given operations on a number ; Function that returns the maximum difference after two given operations on a number ; Initialize the strings to make operations ; Store length of the string ; Make the maximum number using the first operation ; Find the first digit which is not equal to '9' ; Store the digit for the given operation ; Replace all the selected ' digit ' with '9' ; Break after the operation is completed ; Check if first digit is equal to '1' ; Find the first digit which is greater than '1' ; Store the digit for the given operation ; Replace all the selected ' digit ' with '0' ; Break after the operation is completed ; Select the first digit for the given operation ; Replace all the selected ' digit ' with '1' ; Return the difference after converting into integers ; Driver code
import java . util . * ; class GFG { static int minDifference ( int num ) { StringBuilder maximum = new StringBuilder ( Integer . toString ( num ) ) ; StringBuilder minimum = new StringBuilder ( Integer . toString ( num ) ) ; int n = maximum . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( maximum . charAt ( i ) != '9' ) { char digit = maximum . charAt ( i ) ; for ( int j = i ; j < n ; j ++ ) { if ( maximum . charAt ( j ) == digit ) maximum . setCharAt ( j , '9' ) ; } break ; } } if ( minimum . charAt ( 0 ) == '1' ) { for ( int i = 1 ; i < n ; i ++ ) { if ( minimum . charAt ( i ) - '0' > 1 ) { char digit = minimum . charAt ( i ) ; for ( int j = i ; j < n ; j ++ ) { if ( digit == minimum . charAt ( j ) ) minimum . setCharAt ( j , '0' ) ; } break ; } } } else { char digit = minimum . charAt ( 0 ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( minimum . charAt ( i ) == digit ) minimum . setCharAt ( i , '1' ) ; } } return ( Integer . parseInt ( maximum . toString ( ) ) - Integer . parseInt ( minimum . toString ( ) ) ) ; } public static void main ( String [ ] args ) { int N = 1101157 ; System . out . println ( minDifference ( N ) ) ; } }