Untitled

mail@pastecode.io avatar
unknown
plain_text
10 months ago
1.3 kB
2
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);
    }

    public static int findLargestNumberWithChanges(int number, int maxChanges) {
        char[] numArray = Integer.toString(number).toCharArray();
        int length = numArray.length;
        char[] resultArray = new char[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--;
            }

            resultArray[i] = maxDigit;
            numArray[maxIndex] = numArray[i];
        }

        for (int i = 0; i < length; i++) {
            if (resultArray[i] == 0) {
                resultArray[i] = numArray[i];
            }
        }

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