Maximise the sum of two Numbers using at most one swap between them | Python 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 function
MAX = 100 NEW_LINE def findMaxSum ( n1 , n2 ) : NEW_LINE INDENT arr1 = [ 0 ] * ( MAX ) NEW_LINE arr2 = [ 0 ] * ( MAX ) NEW_LINE l1 = 0 NEW_LINE l2 = 0 NEW_LINE max1 = max ( n1 , n2 ) ; NEW_LINE min1 = min ( n1 , n2 ) ; NEW_LINE i = max1 NEW_LINE while i > 0 : NEW_LINE INDENT arr1 [ l1 ] = ( i % 10 ) NEW_LINE l1 += 1 NEW_LINE i //= 10 NEW_LINE DEDENT i = min1 NEW_LINE while i > 0 : NEW_LINE INDENT arr2 [ l2 ] = ( i % 10 ) NEW_LINE l2 += 1 NEW_LINE i //= 10 NEW_LINE DEDENT f = 0 NEW_LINE if ( l1 != l2 ) : NEW_LINE INDENT index = arr2 . index ( max ( arr2 ) ) NEW_LINE for i in range ( l1 - 1 , ( l2 - 1 ) , - 1 ) : NEW_LINE INDENT if ( arr1 [ i ] < arr2 [ index ] ) : NEW_LINE INDENT ( arr1 [ i ] , arr2 [ index ] ) = ( arr2 [ index ] , arr1 [ i ] ) NEW_LINE f = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if ( f != 1 ) : NEW_LINE INDENT index1 = 0 NEW_LINE index2 = 0 NEW_LINE diff1 = 0 NEW_LINE diff2 = 0 NEW_LINE for i in range ( l2 - 1 , - 1 , - 1 ) : NEW_LINE INDENT index1 = arr1 . index ( max ( arr1 [ : i ] ) ) NEW_LINE index2 = arr2 . index ( max ( arr2 [ : i ] ) ) NEW_LINE diff1 = ( arr2 [ index2 ] - arr1 [ i ] ) ; NEW_LINE diff2 = ( arr1 [ index1 ] - arr2 [ i ] ) ; NEW_LINE if ( diff1 > 0 or diff2 > 0 ) : NEW_LINE INDENT if ( diff1 > diff2 ) : NEW_LINE INDENT arr1 [ i ] , arr2 [ index2 ] = arr2 [ index2 ] , arr1 [ i ] NEW_LINE break NEW_LINE DEDENT elif ( diff2 > diff1 ) : NEW_LINE INDENT arr2 [ i ] , arr1 [ index1 ] = arr1 [ index1 ] , arr2 [ i ] NEW_LINE break NEW_LINE DEDENT elif ( diff1 == diff2 ) : NEW_LINE INDENT if ( index1 <= index2 ) : NEW_LINE INDENT arr2 [ i ] , arr1 [ index1 ] = arr1 [ index1 ] , arr2 [ i ] NEW_LINE break NEW_LINE DEDENT elif ( index2 <= index1 ) : NEW_LINE INDENT arr1 [ i ] , arr2 [ index2 ] = arr2 [ index2 ] , arr1 [ i ] NEW_LINE break ; NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT f_n1 = 0 NEW_LINE f_n2 = 0 NEW_LINE for i in range ( l1 - 1 , - 1 , - 1 ) : NEW_LINE INDENT f_n1 = ( f_n1 * 10 ) + arr1 [ i ] NEW_LINE f_n2 = ( f_n2 * 10 ) + arr2 [ i ] NEW_LINE DEDENT print ( f_n1 + f_n2 ) NEW_LINE DEDENT N1 = 9987 NEW_LINE N2 = 123 NEW_LINE findMaxSum ( N1 , N2 ) NEW_LINE