Given a non-negative number num. The problem is to apply at most one swap operation on the number num so that the resultant is the largest possible number. The number could be very large so a string type can be used to store the number.
Input : n = 8725634 Output : 8765234 Swapped the digits 2 and 6. Input : n = 54321 Output : 54321 No swapping of digits required.
Create an array rightMax. rightMax[i] contains the index of the greatest digit which is on the right side of num[i] and also greater than num[i]. If no such digit exists then rightMax[i] = -1. Now, traverse the rightMax array from i = 0 to n-1(where n is the total number of digits in num), and find the first element having rightMax[i] != -1. Perform the swap(num[i], num[rightMax[i]]) operation and break.
Largest number: 8765234
Time Complexity: O(n), where n is the total number of digits.
Auxiliary Space: O(n), where n is the total number of digits.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Form the smallest number using at most one swap operation
- Largest smaller number possible using only one swap operation
- Next higher number using atmost one swap operation
- Largest number with one swap allowed
- Form the largest palindromic number using atmost two swaps
- Minimum possible number with the given operation
- Maximum possible number with the given operation
- Count the total number of triangles after Nth operation
- Generate number with given operation and check if it is palindrome
- Number of ways to color N-K blocks using given operation
- Check if X and Y can be made zero by using given operation any number of times
- Minimum number of given operation required to convert n to m
- Check if the given array can be reduced to zeros with the given operation performed given number of times
- Find the largest number smaller than integer N with maximum number of set bits
- Largest number dividing maximum number of elements in the array
- Number of times the largest perfect square number can be subtracted from N
- Find the largest good number in the divisors of given number N
- Largest number less than N whose each digit is prime number
- Largest even number that can be formed by any number of swaps
- Number of subarrays having sum of the form k^m, m >= 0