Given a positive integer, find maximum integer possible by doing at-most K swap operations on its digits.
Input: M = 254, K = 1 Output: 524 Input: M = 254, K = 2 Output: 542 Input: M = 68543, K = 1 Output: 86543 Input: M = 7599, K = 2 Output: 9975 Input: M = 76543, K = 1 Output: 76543 Input: M = 129814999, K = 4 Output: 999984211
Idea is to consider every digit and swap it with digits following it one at a time and see if it leads to the maximum number. We repeat the process K times. The code can be further optimized if we swap only if current digit is less than the following digit.
Below is implementation of above idea –
The above code can further be optimized by stopping our search if all digits are already sorted in decreasing order. Please do share with us if you find more efficient ways to solve this problem.
1. Find minimum integer possible by doing at-least K swap operations on its digits.
2. Find maximum/minimum integer possible by doing exactly K swap operations on its digits.
This article is contributed by Aditya Goel.If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
- Find the row with maximum number of 1s
- Find triplet such that number of nodes connecting these triplets is maximum
- Find the maximum repeating number in O(n) time and O(1) extra space
- Given an array arr, find the maximum j - i such that arr[j] > arr[i]
- Find maximum possible stolen value from houses
- Find maximum level sum in Binary Tree
- Find maximum average subarray of k length
- Find a pair with maximum product in array of Integers
- Find the maximum path sum between two leaves of a binary tree
- Find maximum of minimum for every window size in a given array
- Find the maximum element in an array which is first increasing and then decreasing
- Write a Program to Find the Maximum Depth or Height of a Tree
- How to print maximum number of A's using given four keys
- Find the smallest number whose digits multiply to a given number n
- Recursively break a number in 3 parts to get maximum sum
Improved By : vibhu4agarwal