Given an integer N in the form of string, the task is to find the largest even number from the given number when you are allowed to do any number of swaps (swapping the digits of the number). If no even number can be formed then print -1.
Input: N = 1324
Input: N = 135
No even number can be formed using odd digits.
Approach: Sort the string in descending order then we will get the largest number possible with the given digit but it may or may not be an even number. In order to make it even (if it not already), an even digit from the number must be swapped with the last digit and in order to maximize the even number the even digit which is to be swapped must the smallest even digit from the number.
Note that the sorting can be done in linear time using frequency array for the digits of the number as the number of distinct elements that are need to be sorted can be at most 10 in the worst case.
Below is the implementation of the above approach:
Time Complexity: O(n)
- Form the largest palindromic number using atmost two swaps
- Find the largest number that can be formed with the given digits
- Find the Largest Cube formed by Deleting minimum Digits from a number
- Find maximum number that can be formed using digits of a given number
- Minimum number of swaps required to sort an array
- Number of swaps to sort when only adjacent swapping allowed
- 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 even number possible by using one swap operation in given number
- Largest number less than N whose each digit is prime number
- Number of triangles that can be formed with given N points
- Check if a number is formed by Concatenation of 1, 14 or 144 only
- Number of triangles formed from a set of points on three lines
- Maximum number of teams that can be formed with given persons
- Length of the smallest number which is divisible by K and formed by using 1's only
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.