Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.4 kB
3
Indexable
Never
import java.util.Scanner;

public class Main {
    
    // Function to calculate the maximum prize
    public static int calculatePrize(int cards, int exchanges) {
        char[] numArray = String.valueOf(cards).toCharArray(); // Convert the number to a character array
        
        int[] maxPrize = new int[1]; // Store the maximum prize
        
        backtrack(numArray, exchanges, maxPrize, 0);
        
        return maxPrize[0];
    }
    
    // Backtracking function to generate all possible permutations and update the maximum prize
    public static void backtrack(char[] numArray, int exchanges, int[] maxPrize, int currentIndex) {
        if (exchanges == 0) {
            int currentPrize = Integer.parseInt(new String(numArray));
            maxPrize[0] = Math.max(maxPrize[0], currentPrize);
            return;
        }
        
        for (int i = currentIndex; i < numArray.length; i++) {
            for (int j = i + 1; j < numArray.length; j++) {
                // Swap the digits at positions i and j
                char temp = numArray[i];
                numArray[i] = numArray[j];
                numArray[j] = temp;
                
                // Continue backtracking with decreased exchanges
                backtrack(numArray, exchanges - 1, maxPrize, i);
                
                // Revert the swap
                temp = numArray[i];
                numArray[i] = numArray[j];
                numArray[j] = temp;
            }
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Read the number of test cases
        int numTestCases = scanner.nextInt();
        scanner.nextLine(); // Consume newline

        // Iterate over each test case
        for (int caseNum = 1; caseNum <= numTestCases; caseNum++) {
            // Read the number cards and the number of exchanges
            int numberCards = scanner.nextInt();
            int numExchanges = scanner.nextInt();
            scanner.nextLine(); // Consume newline
            
            // Calculate the maximum prize for this test case
            int maxPrize = calculatePrize(numberCards, numExchanges);
            
            // Print the result
            System.out.println("Case #" + caseNum);
            System.out.println(maxPrize);
        }

        scanner.close();
    }
}
Leave a Comment