Find the maximum difference after applying the given operations two times 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
function minDifference ( num ) { let maximum = ( num . toString ( ) ) . split ( ' ' ) ; let minimum = ( num . toString ( ) ) . split ( ' ' ) ; let n = maximum . length ; for ( let i = 0 ; i < n ; i ++ ) { if ( maximum [ i ] != ' ' ) { let digit = maximum [ i ] ; for ( let j = i ; j < n ; j ++ ) { if ( maximum [ j ] == digit ) maximum [ j ] = ' ' ; } break ; } } if ( minimum [ 0 ] == ' ' ) { for ( let i = 1 ; i < n ; i ++ ) { if ( minimum [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) > 1 ) { let digit = minimum [ i ] ; for ( let j = i ; j < n ; j ++ ) { if ( digit == minimum [ j ] ) minimum [ j ] = ' ' ; } break ; } } } else { let digit = minimum [ 0 ] ; for ( let i = 0 ; i < n ; i ++ ) { if ( minimum [ i ] == digit ) minimum [ i ] = ' ' ; } } return parseInt ( maximum . join ( " " ) ) - parseInt ( minimum . join ( " " ) ) ; } let N = 1101157 ; document . write ( minDifference ( N ) ) ;