Untitled

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

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

    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;
            }

            int maxDigit = -1;
            int maxIndex = -1;

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

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

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