Another Java brute force solution


  • 0
    Z
    public int maximumSwap(int num) {
    
            String numStr = String.valueOf(num);
    
            char[] numChars = numStr.toCharArray();
    
            for (int i = 0; i < numChars.length; i++) {
    
                char maxDigit = Character.MIN_VALUE;
                int maxPos = -1;
    
                for (int j = numChars.length - 1; j >= i + 1; j--) {
                    if (numChars[i] < numChars[j]) {
                        if (numChars[j] > maxDigit) {
                            maxPos = j;
                            maxDigit = numChars[j];
                        }
                    }
                }
    
                if (maxPos != -1) {
                    char tmp = numChars[i];
                    numChars[i] = numChars[maxPos];
                    numChars[maxPos] = tmp;
                    return Integer.valueOf(String.valueOf(numChars));
                }
            }
    
            return num;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.