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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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
- Generate number with given operation and check if it is palindrome
- Number of ways to color N-K blocks using given operation
- Minimum number of given operation required to convert n to m
- Check if X and Y can be made zero by using given operation any number of times
- Count the total number of triangles after Nth operation
- 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
- Number of times the largest perfect square number can be subtracted from N
- Largest number dividing maximum number of elements in the array
- Find the largest good number in the divisors of given number N
- Largest even number that can be formed by any number of swaps
- Largest number less than N whose each digit is prime number
- Number of subarrays having sum of the form k^m, m >= 0