Largest number with one swap allowed

3.7

Given a positive integer, find the largest number that could be generated by swapping only two digits at most once.

Examples:

Input: 2736
Output : 7236
Explanation:
If we swap the number 2 and the number
7 then the generated number would be 
the largest number.

Input : 432
Output : 432
Explanation:
Here, no swap is required. The given
number is already largest.

Approach 1 (Trying every pair):
We convert the number to a string. For each digit of the number, we will swap with positions (i, j) and store it as temp check if the temp is larger than number. If yes then swap back to restore the original number.

C++

// code to find largest number with
// given conditions.

#include <bits/stdc++.h>
using namespace std;

// function to find the largest number
// with given conditions.
int largestNum(int num)
{
    // converting the number to the string
    string num_in_str = to_string(num);
    string temp = num_in_str;

    // swamping each digit
    for (int i = 0; i < num_in_str.size(); i++) {
        for (int j = i + 1; j < num_in_str.size(); j++) {

            // Swapping and checking for the larger
            swap(num_in_str[i], num_in_str[j]);
            if (stoi(num_in_str) > stoi(temp))
                temp = num_in_str;

            // Reverting the changes
            swap(num_in_str[i], num_in_str[j]);
        }
    }

    return stoi(temp);
}

// driver function
int main()
{
    int num = 432;
    cout << largestNum(num) << endl;
    num = 2736;
    cout << largestNum(num) << endl;
    num = 4596;
    cout << largestNum(num) << endl;
    return 0;
}

Java

// Java code to find largest number
// with given conditions.
public class LargestNumber{ 
    
    static String swap(String str, int i, int j)
    {
        char ch[] = str.toCharArray();
        char temp = ch[i];
        ch[i] = ch[j];
        ch[j] = temp;
        String c=String.valueOf(ch); 
        return c;
    }
    
    // function to find the largest number
    // with given conditions.
    static int largestNum(int num)
    {
        // converting the number to the string
        String num_in_str = ""+num;
        String temp = num_in_str;   

        // swamping each digit
        for (int i = 0; i < num_in_str.length(); i++) {
            for (int j = i + 1; j < num_in_str.length(); 
                                              j++) {

                // Swapping and checking for the larger
                num_in_str= swap(num_in_str,i,j);
                if (temp.compareTo(num_in_str)<0)
                        temp = num_in_str;

                // Reverting the changes
                num_in_str=swap(num_in_str,i,j);
            }
        }

        return Integer.parseInt(temp);
    }

    // Driver code
    public static void main(String[] s)
    {
        int num = 423;
        System.out.println(largestNum(num));
        num = 2736;
        System.out.println(largestNum(num));
        num = 4596;
        System.out.println(largestNum(num));
    }
}

// This code is contributed by Prerena Saini

Python3

# python3 code to find the largest 
# number with given conditions.

# function to find the largest number
def largestNum(num):

    # converting the number to the list
    num_to_str = list(str(num))
    temp = num_to_str[:]

    # swaping each digit and check for
    # the largest number
    for i in range(len(num_to_str)):
        for j in range(i + 1, len(num_to_str)):

            // Swapping current pair
            num_to_str[i], num_to_str[j] = num_to_str[j], num_to_str[i]
            if num_to_str > temp:
                temp = num_to_str[:]

            # Reverting above change before next iteration 
            num_to_str[i], num_to_str[j] = num_to_str[j], num_to_str[i]

    # returning the largest number.
    return int("".join(temp))

# main function
def main():
    A = int(432)
    print(largestNum(A))
    A = int(2736)
    print(largestNum(A))
    A = int(4596)
    print(largestNum(A))

# calling main function
if __name__=="__main__":
    main()


Output:

432
7236
9546

 

Approach 2 (Efficient) :
We will scan the number from backward direction. In the scan, if the ith digit is the largest by far, store it and its index or if the current digit is smaller than the largest digit recorded by far, this digit and the largest digit are the best suitable for swap.

Below is the c++ code for the above approach.

// code to find largest number with
// given conditions.
#include <bits/stdc++.h>
using namespace std;

// function to find the largest number
// with given conditions.
int largestNum(int num)
{
    int max_digit = -1;
    int max_digit_indx = -1;
    int l_indx = -1;
    int r_indx = -1;

    // converting the number to string
    string num_in_str = to_string(num);
    for (int i = num_in_str.size() - 1; i >= 0; i--) {

        // current digit is the largest by far
        if (num_in_str[i] > max_digit) {
            max_digit = num_in_str[i];
            max_digit_indx = i;
            continue;
        }

        // best digit for swap if there is no more
        // such situation on the left side
        if (num_in_str[i] < max_digit) {
            l_indx = i;
            r_indx = max_digit_indx;
        }
    }

    // check for is nummber already in order
    if (l_indx == -1)
        return num;

    swap(num_in_str[l_indx], num_in_str[r_indx]);

    return stoi(num_in_str);
}

// driver function
int main()
{
    int num = 789;
    cout << largestNum(num) << endl;
    num = 49658;
    cout << largestNum(num) << endl;
    num = 2135;
    cout << largestNum(num) << endl;
    return 0;
}

Output:

987
94658
5132

This article is contributed by Abhishek Sharma 44. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geekforgeeks.org or mail your article to contribute@geeksforgeeks.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.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



3.7 Average Difficulty : 3.7/5.0
Based on 8 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.