Maximise the sum of two Numbers using at most one swap between them | JavaScript program to maximise the sum of two Numbers using at most one swap between them ; Function to maximize the sum by swapping only one digit ; Store digits of max ( n1 , n2 ) ; Store digits of min ( n1 , n2 ) ; If length of the two numbers are unequal ; Find the most significant number and the most significant index for swapping ; If both numbers are of equal length ; Fetch the index of current maximum digit present in both the arrays ; Compute the difference ; Find the most significant index and the most significant digit to be swapped ; Restore the new numbers ; Display the maximized sum ; Driver Code
let MAX = 100 ; function max_element ( arr , pos ) { let tmp = arr [ 0 ] ; let ind = 0 ; for ( let i = 1 ; i < pos ; i ++ ) { if ( tmp < arr [ i ] ) { tmp = arr [ i ] ; ind = i ; } } return ind ; } function findMaxSum ( n1 , n2 ) { let arr1 = Array . from ( { length : MAX } , ( _ , i ) => 0 ) ; let arr2 = Array . from ( { length : MAX } , ( _ , i ) => 0 ) ; let l1 = 0 , l2 = 0 ; let max1 = Math . max ( n1 , n2 ) ; let min1 = Math . min ( n1 , n2 ) ; for ( let i = max1 ; i > 0 ; i = Math . floor ( i / 10 ) ) arr1 [ l1 ++ ] = ( i % 10 ) ; for ( let i = min1 ; i > 0 ; i = Math . floor ( i / 10 ) ) arr2 [ l2 ++ ] = ( i % 10 ) ; let f = 0 ; if ( l1 != l2 ) { let index = ( max_element ( arr2 , l2 ) ) ; for ( let i = l1 - 1 ; i > ( l2 - 1 ) ; i -- ) { if ( arr1 [ i ] < arr2 [ index ] ) { let tmp = arr1 [ i ] ; arr1 [ i ] = arr2 [ index ] ; arr2 [ index ] = tmp ; f = 1 ; break ; } } } if ( f != 1 ) { let index1 = 0 , index2 = 0 ; let diff1 = 0 , diff2 = 0 ; for ( let i = l2 - 1 ; i >= 0 ; i -- ) { index1 = ( max_element ( arr1 , i ) ) ; index2 = ( max_element ( arr2 , i ) ) ; diff1 = ( arr2 [ index2 ] - arr1 [ i ] ) ; diff2 = ( arr1 [ index1 ] - arr2 [ i ] ) ; if ( diff1 > 0 diff2 > 0 ) { if ( diff1 > diff2 ) { let tmp = arr1 [ i ] ; arr1 [ i ] = arr2 [ index2 ] ; arr2 [ index2 ] = tmp ; break ; } else if ( diff2 > diff1 ) { let tmp = arr1 [ index1 ] ; arr1 [ index1 ] = arr2 [ i ] ; arr2 [ i ] = tmp ; break ; } else if ( diff1 == diff2 ) { if ( index1 <= index2 ) { let tmp = arr1 [ index1 ] ; arr1 [ index1 ] = arr2 [ i ] ; arr2 [ i ] = tmp ; break ; } else if ( index2 <= index1 ) { let tmp = arr1 [ i ] ; arr1 [ i ] = arr2 [ index2 ] ; arr2 [ index2 ] = tmp ; break ; } } } } } let f_n1 = 0 , f_n2 = 0 ; for ( let i = l1 - 1 ; i >= 0 ; i -- ) { f_n1 = ( f_n1 * 10 ) + arr1 [ i ] ; f_n2 = ( f_n2 * 10 ) + arr2 [ i ] ; } document . write ( f_n1 + f_n2 ) ; } let N1 = 9987 ; let N2 = 123 ; findMaxSum ( N1 , N2 ) ;