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
- Maximise the sum of two Numbers using at most one swap between them
- Largest number with one swap allowed
- Form the largest palindromic number using atmost two swaps
- Find the largest number that can be formed by changing at most K digits
- Generate number with given operation and check if it is palindrome
- Minimum possible number with the given operation
- Form smallest number using indices of numbers chosen from Array with sum less than S
- Largest number divisible by 90 that can be made using 0 and 5
- Minimize the number by changing at most K digits
- Find the Largest number with given number of digits and sum of digits
- Largest number less than N whose each digit is prime number
- Number of times a number can be replaced by the sum of its digits until it only contains one digit
- Arrange given numbers to form the biggest number | Set 2
- Reduce a given number to form a key by the given operations
- Print all numbers less than N with at-most 2 unique digits
- Find the longest subsequence of an array having LCM at most K
- Count of numbers upto N having absolute difference of at most K between any two adjacent digits