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 number that can be formed by changing at most K digits
- Largest number in given Array formed by repeatedly combining two same elements
- Find the Largest Cube formed by Deleting minimum Digits from a number
- Minimum number of swaps required to sort an array of first N number
- Find maximum number that can be formed using digits of a given number
- Number of times the largest perfect square number can be subtracted from N
- Largest number dividing maximum number of elements in the array
- Number of swaps to sort when only adjacent swapping allowed
- Minimum number of swaps required to sort an array
- Find the largest good number in the divisors of given number N
- Minimum number of adjacent swaps to convert a string into its given anagram
- Minimum number of swaps to make two binary string equal
- Largest even number possible by using one swap operation in given number
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.