O(n) time O(n) space, kinda messy though


  • 0
    E
    public int maximumSwap(int num) {
            //find the first number that has a number greater than it to its right
            //take the right-most greatest number (if there are multiple same ones), swap and return
            //else return num
            String input = String.valueOf(num);
            if(input.length() < 2){
                return num;
            }
            char[] out = input.toCharArray();
            int[] max = new int[input.length()];
            int currMax = num % 10;
            for(int i = input.length()-2; i >= 0; i--){
                max[i] = currMax;
                currMax = Math.max(currMax, Character.getNumericValue(input.charAt(i)));
            }
            for(int i = 0; i < input.length(); i++){
                if(max[i] > Character.getNumericValue(input.charAt(i))){
                    int idxToSwap = input.lastIndexOf(String.valueOf(max[i]));
                    out[idxToSwap] = out[i];
                    out[i] = input.charAt(idxToSwap);
                    return Integer.parseInt(new String(out));
                }
            }
            return num;
        }
    

Log in to reply
 

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