Maximise the sum of two Numbers using at most one swap between them
Given two natural numbers N1 and N2, the task is to find the maximum sum possible after swapping of a single digit between them.
Input: N1 = 984788, N2 = 706
Swapping 4 from N1 with 7 from N2, we get N1 = 987788 and N2 = 406
Sum = 988194
Input: N1 = 9987, N2 = 123
Swapping 8 from N1 with 1 from N2, we get N1 = 9917 and N2 = 823
Sum = 10740
- Compare N1 and N2 and store the digits of the larger of the two in array arr1 and that of the smaller in arr2 respectively.
- If both the numbers are of different lengths, find the index of maximum element in arr2, and the most significant index in arr1, and swap them to maximize the sum.
- If both the numbers are of same length,
- Iterate both the arrays arr1 and arr2 at the same time.
- For each digit at index i in both the arrays, find the difference between the current digit and the largest digit left to index ‘i’.
- Compare the difference to find the most significant digit and most significant index, whose value needs to be swapped.
- Restore the new numbers from arr1 and arr2 and calculate the maximized sum.
Below code is the implementation of the above approach:
Time Complexity: O(n)
Auxiliary Space: O(MAX)