0% found this document useful (0 votes)
41 views

Max Swap

The document describes a Java program that takes a string of digits and finds the maximum number that can be formed by swapping adjacent digits up to a specified number of swaps. The program uses recursion to try all possible swaps and keeps track of the maximum number found.

Uploaded by

sukeerth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Max Swap

The document describes a Java program that takes a string of digits and finds the maximum number that can be formed by swapping adjacent digits up to a specified number of swaps. The program uses recursion to try all possible swaps and keeps track of the maximum number found.

Uploaded by

sukeerth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.util.

*;
public class Ash{

static String max;

static void findMaximumNum(char[] N, int M)


{
// Return if no swaps left
if (M == 0)
return;

int n = N.length;

// Consider every digit


while(M>0){
for (int i = 0; i < n - 1; i++)
{

for (int j = i + 1; j < n; j++)


{
// if digit at position i
// is less than digit
// at position j, swap it
// and check for maximum
// number so far and recurse
// for remaining swaps
if (N[i] < N[j])
{
// swap N[i] with
// N[j]
char t = N[i];
N[i] = N[j];
N[j] = t;

// If current num is more


// than maximum so far
if (String.valueOf(N).compareTo(max) > 0)
max = String.valueOf(N);

// recurse of the other


// M - 1 swaps
findMaximumNum(N, M - 1);

// Backtrack
char c = N[i];
N[i] = N[j];
N[j] = c;
M--;
}
}
}
}
}

// Driver code
public static void main(String[] args)
{
String N = "1123";
int M = 1;
max = N;
findMaximumNum(N.toCharArray(), M);
System.out.print(max + "\n");
}
}

You might also like