Untitled

mail@pastecode.io avatar
unknown
plain_text
8 months ago
1.4 kB
1
Indexable
Never
public class Main {
    public static void main(String[] args) {
        int number = 2737;
        int maxChanges = 1;

        int result = findLargestNumberWithChanges(number, maxChanges);
        System.out.println("Largest number with " + maxChanges + " changes: " + result);

        int number2 = 32888;
        int maxChanges2 = 2;

        int result2 = findLargestNumberWithChanges(number2, maxChanges2);
        System.out.println("Largest number with " + maxChanges2 + " changes: " + result2);
    }

    public static int findLargestNumberWithChanges(int number, int maxChanges) {
        char[] numArray = Integer.toString(number).toCharArray();
        int length = numArray.length;

        for (int i = 0; i < length; i++) {
            if (maxChanges == 0) {
                break;
            }

            char maxDigit = numArray[i];
            int maxIndex = i;

            for (int j = i + 1; j < length; j++) {
                if (numArray[j] > maxDigit) {
                    maxDigit = numArray[j];
                    maxIndex = j;
                }
            }

            if (maxDigit > numArray[i]) {
                maxChanges--;
                char temp = numArray[i];
                numArray[i] = numArray[maxIndex];
                numArray[maxIndex] = temp;
            }
        }

        return Integer.parseInt(new String(numArray));
    }
}